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)