相比较于线性查找,二分查找算法是查找数组中元素的高效方法,它生成一棵二分查找树,复杂度为O(log2n)。
当然前提是数组有序。
import java.util.Scanner;
public class BinarySearch {
public static int binarySearch(int[] arr, int purpose) {
int bottom = 0;
int top = arr.length - 1;
while (bottom <= top) {
int mid = (bottom + top) / 2;
if (arr[mid] == purpose)
return mid;
else if (arr[mid] > purpose)
top = mid - 1;
else
bottom = mid + 1;
}
return -1;
}
public static int recursiveBinarySearch(int[] arr, int purpose, int bottom ,int top) {
if (bottom > top)
return -1;
int mid = (bottom + top) / 2;
if (arr[mid] == purpose)
return mid;
return arr[mid] > purpose ? recursiveBinarySearch(arr, purpose, bottom, mid - 1) :
recursiveBinarySearch(arr, purpose, mid + 1, top);
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Scanner input = new Scanner(System.in);
System.out.print("Enter the number you want to find: ");
int num = input.nextInt();
int index = recursiveBinarySearch(arr, num, 0, arr.length - 1);
if (index == -1) {
System.out.println("Sorry ! it's NOT FOUND");
System.exit(0);
}
System.out.printf("Find! It's index is %d\n", index);
}
}

本文介绍了一种高效的查找数组元素的方法——二分查找算法,并通过Java实现递归和非递归两种方式。该算法的前提是数组必须有序,其时间复杂度为O(log2n),相较于线性查找更高效。

3834

被折叠的 条评论
为什么被折叠?



