(数组练习)二分法查找

package com.chihuo.myCollection;


import java.util.Arrays;
/**
 * 比较普通查找和二分法查找所需次数
 * @author ASUS
 *
 */
public class BinarySearch {
public static void main(String[] args){
int[] arr ={12,123,112,33,11,5,7,999,66,9999,663};
System.out.println(Arrays.toString(arr));
System.out.println(ConmonSearch(arr,663));
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
System.out.println(BinaryCounts(arr,5));
}
//普通查找
public static int ConmonSearch(int [] arr,int a){
int counts = 0;
for(int i = 0;i counts++;
if(arr[i]==a){
break;
}
}
return counts;
}

//二分法查找
public static int BinaryCounts(int [] arr,int a){
int counts = 0;
int index = 0;
int start = 0;
int end = arr.length-1;
if(end>0){
for(int i=0;i counts++;
index=(start+end)/2;
if(arr[index] start = index;
}else if(arr[index]>a){
end=index;
}else{
break;

}
}
return counts;

}
return -1;
}
}

你可能感兴趣的:((数组练习)二分法查找)