rt
直接贴代码
#include <iostream>
#include <string>
using namespace std;
int normal_find(int *data, int length, int value){
int head = 0, tail = length-1;
int pos = -1;
while(head<=tail){
int mid = (tail+head)/2;
mid = (tail-head)/2+head;
if(value==data[mid]){
pos = mid;
break;
}
else if(value<data[mid])
tail = mid-1;
else
head = mid+1;
}
return pos;
}
int normal_find2(int *data, int length, int value){
int head = 0, tail = length-1;
while(head<tail){
cout<<"xx:"<<head<<","<<tail<<endl;
int mid = (tail+head)/2;
if(value<=data[mid])
tail = mid;
else
head = mid+1;
}
cout<<"xx:"<<head<<","<<tail<<endl;
if(value==data[head])
return head;
else
return -1;
}
int main(int argc, char** argv){
int value;
if(argc==2)
value = atoi(argv[1]);
else
value = 16;
int a[] = {1,2,3,4,5,6,7,8,9,16,18,19,22};
int length = sizeof(a) / sizeof(int);
int res = normal_find(a, length, value);
cout<<"pos:"<<res<<" value:"<<a[res]<<endl;
res = normal_find2(a, length, value);
cout<<"pos:"<<res<<" value:"<<a[res]<<endl;
return 0;
}