Today in the company idle egg, online blind visit, accidentally saw an article on InfoQ Website "the most important computer science 32 algorithms", the original address: http://www.infoq.com/cn/news/2012/08/32-most-important-algorithms? Utm_source = infoq & utm_medium = popular_links_homepage. There is a binary search algorithm in it, so you can implement this algorithm to see if you have mastered it. It takes only half a day to write it out, so you can feel ashamed. Write down this article to review the binary search algorithm and alert yourself.
I. Concepts
The binary search algorithm is also called the semi-query algorithm. It is a search algorithm used to search for a specific element in an ordered array.
Ii. algorithm ideas
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.
Iii. Advantages and Disadvantages
The advantage of the binary search algorithm is that the query speed is fast and the average performance is good. The disadvantage is that the table to be queried must be an ordered table and it is difficult to insert or delete the table. Therefore, the binary search algorithm is suitable for searching frequently ordered lists without frequent changes.
Iv. Complexity Analysis
(1) time complexity
Binary Search reduces the search area by half each time, and the time complexity is. (N indicates the number of elements in the set)
(2) spatial complexity
.
V. Code Implementation
(1) iterative implementation
01 |
public static int binarySearch( int [] arr, int target) { |
06 |
int mid = (bot + top) >>> 1 ; |
07 |
if (target > arr[mid]) { |
09 |
} else if (target < arr[mid]) { |
(2) Recursive Implementation
02 |
* Recursive Binary Search Algorithm |
10 |
public static int binarySearch( int [] arr, int fromIndex, int toIndex, int target) { |
11 |
while (fromIndex <= toIndex) { |
13 |
int mid = (fromIndex + toIndex) >>> 1 ; |
14 |
if (arr[mid] < target) { |
15 |
return binarySearch(arr, mid + 1 , toIndex, target); |
16 |
} else if (arr[mid] > target) { |
17 |
return binarySearch(arr, fromIndex, mid - 1 , target); |
Conclusion: 1. overflow was not taken into account when writing code.
2. Recursive Implementation was not expected.