即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

查找之折半查找

编程语言 m0_37032564 19℃ 0评论
#include
#define N 10

void QuickSort(int a[],int left, int right);
int BinSearch(int a[], int low, int high, int key);
int main()
{
 int a[N] = {2,8,4,9,7,6,5,3,1,0};
 int j = 0, i;
 QuickSort(a, 0, sizeof(a)/sizeof(a[0])-1);
 i = BinSearch(a, 0, N-1, 6);
 printf("%d\n", i);
 for(j = 0; j < N; j++){
  printf("%d ",a[j]);
 }
 printf("\n");
 return 0;
}
//折半查找
int BinSearch(int a[], int low, int high, int key){
 while(low <= high){
  int mid = (low + high) / 2;
  if(a[mid] < key)
   low = mid + 1;
  else if(a[mid] > key)
   high = mid - 1;
  else
   return mid;  //查找成功
 } 
 
 return -1; //查找失败
}

void QuickSort(int a[],int left, int right){
 int key = a[left];
 int i = left;
 int j = right;
 if(left >= right){
  return;
 }
 while(i < j){
  while(i= key){
   j--;
  }
  a[i] = a[j];
  while(i


转载请注明:CodingBlog » 查找之折半查找

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情