Java Binary Search Algorithm
Binary search, also known as binary search, is a search algorithm used to search for a specific element in an ordered array. The search process starts from the intermediate element of the array. If the intermediate element is the element to be searched, the search process ends. If a specific element is greater than or less than the intermediate element, search in the half where the array is greater than or less than the intermediate element, and compare it from the intermediate element as before. If the array in a step is empty, it indicates that no value can be found. This search algorithm reduces the search range by half for each comparison.
- Time Complexity: half-fold searches reduce the search area by half each time, and the time complexity is O (log n ). (N indicates the number of elements in the set)
- Space complexity: O (1 ). Although defined in recursion form, tail recursion can be rewritten as a loop.
Code Description Recursion
intbinarysearch(int array[], int low, int high, int target) { if (low > high) return -1; int mid = (low + high) / 2; if (array[mid] > target) return binarysearch(array, low, mid - 1, target); if (array[mid] < target) return binarysearch(array, mid + 1, high, target); return mid;}
Non-recursion
intbsearchWithoutRecursion(int a[], int key) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; if (a[mid] > key) high = mid - 1; else if (a[mid] < key) low = mid + 1; else return mid; } return -1;}
Defects of the Binary Search Method
The binary search method O (log n) makes it a very efficient algorithm. However, its defects are also so obvious. Just above its limitation: It must be ordered, and it is difficult to ensure that our arrays are all ordered. Of course, you can sort the array when building it, but it falls into the second bottleneck: it must be an array.
The array Read efficiency is O (1), but the efficiency of inserting and deleting an element is O (n ). As a result, building an ordered array becomes inefficient.
A better way to solve these defects is to use the binary search tree. It is best to use the self-balancing binary search tree, which is efficient (O (n log n )) the number of search targets that can be quickly (O (log n) as the binary search method can be used to construct an ordered element set.