二分搜索是一种搜索算法,用于在已排序的数组中查找元素的位置。
在这种方法中,总是在数组一部分的中间搜索元素。
二分搜索只能在排序的项目列表上实现。如果元素尚未排序,我们需要先对它们进行排序。
算法的图解
二分搜索算法可以通过下面讨论的两种方式实现。
- 迭代法
- 递归法
递归方法遵循分而治之的方法。
下面讨论这两种方法的一般步骤:
- 要在其中执行搜索的数组是:
设 x = 4 为要搜索的元素。 |
|
| —- |
| 初始数组 |
- 分别在最低和最高位置设置两个指针低和高。
|
|
| —- |
| 设置指针 |
- 找到数组的中间元素mid,即:arr[(low + high)/2] = 6
|
|
| —- |
| 中间元素 |
如果 x == mid,则返回 mid.Else,将要搜索的元素与 m 进行比较。
如果 x > mid,则将 x 与 mid 右侧元素的中间元素进行比较。这是通过将低设置为低 = mid + 1 来完成的。
否则,将 x 与 mid 左侧元素的中间元素进行比较。这是通过将 high 设置为 high = mid - 1 来完成的。 |
|
| —- |
| 寻找中间元素 |
- 重复步骤 3 到 6,直到低遇到高。
|
|
| —- |
| 中间元素 |
- x = 4 被发现。
|
|
| —- |
| 找到元素 |
算法的伪码
迭代法
do until the pointers low and high meet each other.mid = (low + high)/2if (x == arr[mid])return midelse if (x > arr[mid]) // x is on the right sidelow = mid + 1else // x is on the left sidehigh = mid - 1
递归法
binarySearch(arr, x, low, high)if low > highreturn Falseelsemid = (low + high) / 2if x == arr[mid]return midelse if x > arr[mid] // x is on the right sidereturn binarySearch(arr, x, mid + 1, high)else // x is on the right sidereturn binarySearch(arr, x, low, mid - 1)
算法的实现
迭代法
// Binary Search in Javaclass BinarySearch {int binarySearch(int array[], int x, int low, int high) {// Repeat until the pointers low and high meet each otherwhile (low <= high) {int mid = low + (high - low) / 2;if (array[mid] == x)return mid;if (array[mid] < x)low = mid + 1;elsehigh = mid - 1;}return -1;}public static void main(String args[]) {BinarySearch ob = new BinarySearch();int array[] = { 3, 4, 5, 6, 7, 8, 9 };int n = array.length;int x = 4;int result = ob.binarySearch(array, x, 0, n - 1);if (result == -1)System.out.println("Not found");elseSystem.out.println("Element found at index " + result);}}
递归法
// Binary Search in Javaclass BinarySearch {int binarySearch(int array[], int x, int low, int high) {if (high >= low) {int mid = low + (high - low) / 2;// If found at mid, then return itif (array[mid] == x)return mid;// Search the left halfif (array[mid] > x)return binarySearch(array, x, low, mid - 1);// Search the right halfreturn binarySearch(array, x, mid + 1, high);}return -1;}public static void main(String args[]) {BinarySearch ob = new BinarySearch();int array[] = { 3, 4, 5, 6, 7, 8, 9 };int n = array.length;int x = 4;int result = ob.binarySearch(array, x, 0, n - 1);if (result == -1)System.out.println("Not found");elseSystem.out.println("Element found at index " + result);}}
算法复杂度
时间复杂度
- 最佳情况复杂度:O(1)
- 平均案例复杂度:O(log n)
- 最坏情况复杂度:O(log n)
空间复杂度
- 二分查找的空间复杂度为O(1)。
算法的应用
- 在 Java、.Net、C++ STL 库中
- 在调试时,二分查找用于查明错误发生的位置。
