题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
import java.util.*; public class Test{ //查找插入点-直接循环查找 public void insert(int num,int[] a){ int flag=0; for(int i=0;i<a.length;i++){ if((a[i]<=num&&num<=a[i+1])||(a[i]>=num&&num>=a[i+1])){ flag=i; break; } } doo(flag,num,a); } //二叉查找解法?没用过的查找方法 //m 为要二叉查找的起始索引,n 为结束索引 public void insert2(int num,int[] a,int m,int n){ int index = (n-m)/2+m; if((a[index]<=num&&num<=a[index+1])||(a[index]>=num&&num>=a[index+1])) { doo(index,num,a); }else{ if(isWhat(a)){ if(num>a[index]) insert2(num,a,index,a.length); else insert2(num,a,m,index); }else{ if(num>a[index]) insert2(num,a,m,index); else insert2(num,a,index,a.length); } } } //判断是升序还是降序 public boolean isWhat(int[] a){ for(int i=0;i<a.length;i++){ if(a[i]<a[i+1]){ return true; }else if(a[i]==a[i+1]) continue; else return false; } return false; } //执行插入的方法 public void doo(int flag,int num,int[] a){ int[] b = new int[a.length+1]; for(int i=0;i<b.length;i++){ if(i<=flag) b[i]=a[i]; else if(i==flag+1) b[i]=num; else b[i]=a[i-1]; System.out.print(b[i]+" "); } System.out.println(); } public static void main(String args[]){ int[] a={1,2,3,4,6,7,9,16,49}; int[] b={9,6,4,3,2,1}; Scanner scan = new Scanner(System.in); System.out.println("input a num: "); int num=scan.nextInt(); new Test().insert(num,a); System.out.println("-------------"); new Test().insert(num,b); System.out.println("=============="); new Test().insert2(num,a,0,a.length); System.out.println("-------------"); new Test().insert2(num,b,0,b.length); } } /*---运行输出--- C:\>java Test input a num: 8 1 2 3 4 6 7 8 9 16 49 ------------- 9 8 6 4 3 2 1 ============== 1 2 3 4 6 7 8 9 16 49 ------------- 9 8 6 4 3 2 1 */