1 --无序查找 2 public static int Search(int[] a,int key){ 3 for(int i=0;i<a.length;i++){ 4 if(key==a[i]){ 5 return i; 6 } 7 } 8 return -1; 9 }
1 --折半查找 2 public static int BinarySearch(int[] a,int key){ 3 int min,max,mid; 4 min=0; 5 max=a.length-1; 6 mid =(min+max)/2; 7 while(key!=a[mid]){ 8 if(key>a[mid]){ 9 min=mid+1; 10 }else{ 11 max=mid-1; 12 } 13 if(max<min) 14 return -1; 15 16 mid=(min+max)/2; 17 } 18 return mid; 19 }
1 --折半查找优化 2 public static int BinarySearch_2(int[] a,int key){ 3 int min,max,mid; 4 min=0; 5 max=a.length-1; 6 while(max>=min){ 7 mid =(min+max)>>1; 8 if(key>a[mid]){ 9 min=mid+1; 10 }else if(key<a[mid]){ 11 max=mid-1; 12 }else{ 13 return mid; 14 } 15 } 16 return -1; 17 }