二进制树型搜索算法
Binary Search is applied on the sorted array or list of large size. It's time complexity of O(log n) makes it very fast as compared to other sorting algorithms. The only limitation is that the array or list of elements must be sorted for the binary search algorithm to work on it.
二进制搜索应用于排序后的数组或大型列表。 O(log n)的时间复杂性使其与其他排序算法相比非常快。 唯一的限制是必须对元素的数组或列表进行排序,以便二进制搜索算法可以对其进行处理。
实现二进制搜索算法 (Implementing Binary Search Algorithm)
Following are the steps of implementation that we will be following:
以下是我们将要执行的实现步骤:
Start with the middle element:
从中间元素开始:
- target value is equal to the middle element of the array, then return the index of the middle element.目标值等于数组的中间元素,则返回中间元素的索引。
-
- If the target value is greater than the number in the middle index, then pick the elements to the right of the middle index, and start with Step 1.
- If the target value is less than the number in the middle index, then pick the elements to the left of the middle index, and start with Step 1.
When a match is found, return the index of the element matched.
找到匹配项后,返回匹配元素的索引。
If no match is found, then return
-1
如果找不到匹配项,则返回
-1
/*
function for carrying out binary search on given array
- values[] => given sorted array
- len => length of the array
- target => value to be searched
*/
int binarySearch(int values[], int len, int target)
{
int max = (len - 1);
int min = 0;
int guess; // this will hold the index o