基本介绍
package algorithm;
public class BinarySearchDemo {
public static void main(String[] args) {
int[] arr = {1,3,8,10,11,67,100};
System.out.println(binarySearchByNonRecursion(arr,67) != -1 ? "查找成功!" : "查找失败!");
System.out.println(binarySearchByRecursion(arr, 0, arr.length - 1, 67) != -1 ? "查找成功!" : "查找失败!");
}
// 非递归(返回查找元素的下标)
public static int binarySearchByNonRecursion(int[] arr, int searchVal) {
int left = 0;
int right = arr.length - 1;
while(left <= right) {
int mid = (left + right) >> 1;
if (arr[mid] == searchVal) {
return mid;
} else if (arr[mid] > searchVal) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
// 递归(返回查找元素的下标)
public static int binarySearchByRecursion(int[] arr, int left, int right, int searchVal) {
if (left > right) { // 递归结束条件
return -1;
}
int mid = (left + right) >> 1;
if (arr[mid] == searchVal) {
return mid;
} else if (arr[mid] > searchVal) {
return binarySearchByRecursion(arr, left, mid - 1, searchVal);
} else {
return binarySearchByRecursion(arr, mid + 1, right, searchVal);
}
}
}