A typical example of a binary search algorithm using a divide-and-conquer strategy.
Given the ordered n elements a[0...n-1], now find a specific element x in these n elements.
The first thing to think about is to use sequential search methods to compare elements in a[0...n-1] until you find the element x or search the entire array to make sure that X is not there. This algorithm does not make good use of the condition that n elements are already ordered, so in the worst case, the sequential search method requires an O (n) comparison.
The binary search method takes full advantage of the order relationship between elements and uses the divide-and-conquer strategy to complete the search task in the worst case with O (logn) time.
The basic idea of a binary search algorithm is to divide n elements into two halves of roughly the same number, taking A[N/2] and X. If x = A[n/2], then X is found and the algorithm terminates. If X<A[N/2], all you need to do is to continue searching for X in the left half of array a. If X>A[N/2], simply continue searching for x in the right half of array A.
1#include <stdio.h>2 3 intBinarySearch (int*a,intXintN)4 {5 intleft =0;6 intright = N-1;7 while(Left <Right )8 {9 intMiddle = (left + right)/2;Ten if(x = =A[middle]) One returnMiddle; A if(X >A[middle]) -left = middle +1; - Else theright = Middle-1; - } - return-1; - } + - intMainvoid) + { A inta[6] = {1,2,3,4,5,6}; at intx; - -scanf"%d", &x); - if(BinarySearch (A, X,6) != -1) -printf"Find"); - Else inprintf"No"); - to return 0; +}
It is easy to see that the size of the array to be searched is reduced by half, without executing the algorithm's while loop. Therefore, in the worst case, the while loop is executed O (Logn) times. The loop in vivo operation requires O (1) time, so the computational time complexity of the entire algorithm in the worst case is O (logn).
Two-part search technology