Two-part search technology

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.