《编程珠玑》之编写正确的程序
把t在数组x中第一个出现的位置返回给p(如果存在多个t的话,原始的算法会任意返回其中的一个),要求代码对数组元素进行对数次比较(该任务可以在log2(n)次比较之内完成)。
1、迭代版本
1 public static int bSearch_Iteration(int t,int left,int right){ 2 int mid; 3 while(left<=right){ 4 count2++; 5 mid=(left+right)/2; 6 if(a[mid]==t){ 7 index=mid; 8 right=mid-1; 9 } 10 else if(a[mid]>t){ 11 right=mid-1; 12 } 13 else{ 14 left=mid+1; 15 } 16 } 17 return index; 18 }
2、递归版本
1 public static int bSearch_Recursion(int t,int left,int right){ 2 int mid=(left+right)/2; 3 if(left<=right){ 4 count1++; 5 if(a[mid]==t){ 6 index=mid; 7 bSearch_Recursion(t,left,mid-1); 8 } 9 else if(a[mid]>t){ 10 bSearch_Recursion(t,left,mid-1); 11 } 12 else { 13 bSearch_Recursion(t,mid+1,right); 14 } 15 16 } 17 return index; 18 19 }
3、主函数及辅助函数
1 private static int a[]={1,7,3,2,2,2,12,9,9,4,11,10}; 2 private static int index=-1; 3 private static int count1=0; 4 private static int count2=0; 5 public static void main(String[] args) throws IOException{ 6 BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); 7 System.out.print("Enter t:"); 8 String str=stdin.readLine(); 9 int t=Integer.parseInt(str); 10 sort(0,a.length-1); 11 for(int i=0;i<a.length;i++){ 12 System.out.print(a[i]+" "); 13 } 14 int p1=bSearch_Recursion(t,0,a.length-1); 15 System.out.println(); 16 System.out.println("元素个数n为:"+a.length); 17 System.out.println("递归法的比较次数是:"+count1); 18 System.out.println("第一次出现"+t+"位置在"+p1); 19 int p2=bSearch_Iteration(t,0,a.length-1); 20 System.out.println("迭代法的比较次数是:"+count2); 21 System.out.println("第一次出现"+t+"位置在"+p2); 22 } 23 public static void sort(int left,int right){ 24 int begin=left; 25 int end=right; 26 int key=a[left]; 27 while(left<right){ 28 while(left<right&&key<=a[right]) 29 right--; 30 if(left<right){ 31 swap(left,right); 32 } 33 while(left<right&&a[left]<=key) 34 left++; 35 if(left<right){ 36 swap(left,right); 37 } 38 } 39 if(begin<left-1) 40 sort(begin,left-1); 41 if(left+1<end) 42 sort(left+1,end); 43 } 44 public static void swap(int i,int j){ 45 int temp=a[i]; 46 a[i]=a[j]; 47 a[j]=temp; 48 }
4、运行结果
Enter t:9
1 2 2 2 3 4 7 9 9 10 11 12
元素个数n为:12
递归法的比较次数是:4
第一次出现9位置在7
迭代法的比较次数是:4
第一次出现9位置在7