C++从入门到放弃 - 折中法找元素位置
原题:
折半查找法找出一个数在 有序数组中的第几个元素的值,也可能不在数组中
int n[15] = { 1432,1235,1145,1024,768,666,555,456,435,345,256,234,218,100,99 };
int t;
cin >> t;
int min=0, max = 14;
bool isfind=false;
while (min<=max)
{
int center = (min + max) / 2;
if (t == n[center]) {
cout << "找到了,在数组中的位置为:" << center<<'\n';
isfind = true;
break;
}
else if(t > n[center]){
max-=2;
}
else {
min+=2;
}
}
if(!isfind)
cout << "找不到";