最小二分法 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

   

#include <stdio.h>int binsearch(int x, int v[], int n){ int left = 0; int right = n - 1; while (left <= right) {  int mid = (left + right)/2;  if (v[mid] < x)  {   left = mid + 1;  }  else if (v[mid] == x)  {   return mid;  }  else  {   right = mid - 1;  } } return -1;}int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int key = 0; int sz = sizeof(arr) / sizeof(arr[0]); scanf("%d", &key); int ret = binsearch(key, arr, sz); if (ret == -1) {  printf("not exist\n"); } else {  printf("%d\n", ret); } system("pause"); return 0;}

最新文章