About C language dichotomy

dichotomy

Adaptation: the number of ordered data to find a number, the actual application will be applied to the Bubble Act sorting methods

The basic idea: a selected group of numbers ranked intermediate position of a number compared with the number of the check to see whether the find the number, if not, use ordering data can be determined by looking at the number of selected numbers before or after, so you can quickly find narrow half. In the same way in selected areas in search, every time and drill down by half, thus quickly find several purposes.

 

Example: Suppose a data in the array is sorted in ascending order: -12 0,616,235,680,100,110,115, enter a number from the keyboard, it is determined whether the number in the array, if the output where the serial number.

#define M 10
#include <stdio.h>
int main(){
  int a[M]={-12,0,6,16,23,56,80,100,110,115};
  int low,mid,high,b,found;
  low=0;
  high=M-1;
  scanf("%d",&b);
  while(low <= high){
    mid=(low+high)/2;
    if(b == a[mid]){
      found =1;
      break;
    }else if(b>a[mid]){
      low=mid+1;
    }else{
      high=mid-1;
    }
  }
  if(found ==1){
    printf("The index of %d is %d",b,mid);
  }else{
    printf("There is not %d",b);
  }
  return 0;
}

 

Guess you like

Origin www.cnblogs.com/jcfeng/p/11303832.html