Java查找
一、二分查找
/**
* <p>Title: HalfSearch</p>
* <p>Description: </p>
* @author zsd
* @date 2020年2月20日
*/
public class HalfSearch {
/**
* 主函数
* <p>Title: main</p>
* <p>Description: 主函数</p>
* @param args
*/
public static void main(String[] args) {
int[] arr = newArray();
int num = searchn(arr, 7);
System.out.println("查到的数为:" + num);
}
/**
* 创建一个数组
* <p>Title: newArray</p>
* <p>Description: 创建一个数组</p>
* @return
*/
private static int[] newArray() {
int[] array = new int[] {1, 2, 3, 5, 7, 9 ,10, 14, 16, 20};
return array;
}
/**
* 查找
* <p>Title: search</p>
* <p>Description: 查找</p>
* @param arr
* @param key
* @return
*/
private static int search1(int[] arr, int key) {
int max, min, mid;
max = arr.length - 1;
min = 0;
mid = (max + min) / 2;
while (arr[mid] != key) {
if (key > arr[mid]) {
min = mid + 1;
} else if (key < arr[mid]) {
max = mid - 1;
}
if (max < min) {
return -1;
}
mid = (max + min) / 2;
}
return mid;
}
/**
* 查找
* <p>Title: search</p>
* <p>Description: 查找</p>
* @param arr
* @param key
* @return
*/
private static int search2(int[] arr, int key) {
int max, min, mid;
max = arr.length - 1;
min = 0;
while (min <= max) {
mid = (max + min) / 2;
if (key > arr[mid]) {
min = mid + 1;
} else if (key < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}
}