快速查找得出索引位置

2/10/2017来源:ASP.NET技巧人气:2175

#include<iostream> using namespace std;

int Find(int ar[],int low,int high,int key) {  if(low>high)   return -1;  int mid = (low+high)/2;  if(ar[mid] == key)   return mid;  else if(key<ar[mid])   return Find(ar,low,mid-1,key);  else   return Find(ar,mid+1,high,key); } void main() {  int ar[]={1,23,45,67,90,123,456,678,900,1000};  int key;  cout<<"intput key:";  cin>>key;  int n = sizeof(ar) / sizeof(int);  int low = 0;  int high = n-1;  int index=Find(ar,low,high,key);  cout<<"index ="<<index<<endl; }