举例:
package BasicSearchCode;
//二分查找 数组内数字有序
public class text3 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
halfsearch(arr,4);
}
public static int halfsearch(int[] arr,int num){
int min;
int max;
for (int i = 0; i < arr.length; i++) {
min = 0;
max = arr.length;
int mid = (min+max)/2;
if (num>arr[mid]){
min = mid+1;
}else if (num<arr[mid]){
mid = max-1;
}else if (min>max){
return -1;
}
else {
System.out.println("找到了"+num+"在数组中第"+mid+"个");
break;
}
}
return -1;
}
}
改进:(插值查找)
要求:数字插值分布均匀
改进:斐波那契查找