二分查找(非递归实现和递归实现)
public class BinarySearch {
//非递归实现
public static int binarySearch(int array[], int low, int high, int key) {
while (low <= high) {
int middle = (low + high) / 2;
if (array[middle] == key) {
return array[middle];
} else if (array[middle] > key) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
//递归实现
public static int binarySearch2(int[] array, int low, int high, int key) {
if (low > high) {
return -1;
} else {
int middle = (low + high) / 2;
if (array[middle] == key) {
return array[middle];
} else if (array[middle] > key) {
return binarySearch2(array, low, middle - 1, key);
} else {
return binarySearch2(array, middle + 1, high, key);
}
}
}
public static void main(String[] args) {
int a[] = { 2, 4, 6, 5, 8, 9 };
int reslut = binarySearch2(a, 0, a.length - 1, 1);
System.out.println("result : " + reslut);
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/13818.html