import java.util.Arrays;
public class Hello {
public static void main(String[] args) {
int[] arr = { 11, 55, 88, 111, 25, 67, 78, 95, 99, 66, 77, 33, 44, 22, 66 };
int searchWord = 55; // 所要查找的数
System.out.printf("普通循环查找%d的次数是%d", searchWord, genetalLoop(arr, searchWord));
System.out.printf("二分法查找%d的次数是%d", searchWord, binarySearch(arr, searchWord));
}
/**
* 普通方法
* @param arr 数组
* @param searchWord 查询的数
* @return
*/
static int genetalLoop(int[] arr, int searchWord) {
int searchCount = 0;
for (int i = 0; i < arr.length; i++) {
searchCount++;
if (searchWord == arr[i])
break;
}
return searchCount;
}
/**
* 二分法
* @param arr 数组
* @param searchWord 查询的数
* @return
*/
static int binarySearch(int[] arr, int searchWord) {
Arrays.sort(arr); // 先对传进来的数组进行排序
System.out.println("\n" + Arrays.toString(arr));
// 二分法查找
int iIndex = 0; // 相当于指针的东西
int iStart = 0;
int iEnd = arr.length - 1;
int searchCount = 0;
for (int i = 0; i < arr.length / 2; i++) {
searchCount++;
iIndex = (iStart + iEnd) / 2;
if (arr[iIndex] < searchWord) {
System.out.println("大了");
iStart = iIndex;
} else if (arr[iIndex] > searchWord) {
System.out.println("小了");
iEnd = iIndex;
} else {
break;
}
}
return searchCount;
}
}