Binary find (binary search)

Source: Internet
Author: User

In an ordered array, the idea of the dichotomy is used to find the contents of the array.

#include  <stdio.h> #include  <stdlib.h> int binsearch (int x,int arr[], Int left,int right) {    while  (left<=right)    {        int mid=left-(left-right)/2;        if (arr[mid]==x)        {            return mid;        }        else if (arr[mid]<x)        {            left=mid+1;       }            else           {               right=mid-1;    &Nbsp;     }    }return -1;}  int main () {     int arr[]={1,3,44,55,102,129,700};      int ret=binsearch (44,arr,0,sizeof (arr)/sizeof (arr[0]-1));    //Find 44      if (ret!=-1)      {          printf ("%d\n", Arr[ret]);      }     else      {         printf ("not exist\n");       }return 0;}

For the program, you need to define the intermediate array elements, generally think of the average int mid= (left+right)/2, but this method has a disadvantage, when the data is large, there may be overflow, so the program uses int mid=left-(left-right)/ 2; This is just the right way to avoid this mistake.



This article from "Unintentional persistent" blog, declined reprint!

Binary find (binary search)

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.