折半查找
程序员文章站
2024-03-20 18:42:04
...
[size=large]最近被人问题,事隔三年了,貌似没什么进步,又写了一遍。[/size]
#include <iostream>
#include <string>
using namespace std;
int binary(int array[], int size, int tag);
int main(int argc, char *argv[])
{
int array[10] = {0, 11, 22, 33, 44, 55, 66, 77, 88, 99};
cout << binary(array, 10, 0) << endl;
cout << binary(array, 10, 99) << endl;
cout << binary(array, 10, 55) << endl;
cout << binary(array, 10, -23) << endl;
cout << binary(array, 10, 123) << endl;
return 0;
}
int binary(int array[], int size, int tag)
{
int beg = 0;
int end = size - 1;
int pos = 0;
while (beg <= end)
{
pos = (beg + end) / 2;
if (array[pos] == tag) return pos;
if (tag > array[pos])
beg = pos + 1; // tag 在右边
else
end = pos - 1; // tag 在左边
}
return -1;
}
上一篇: 代码生成器-zfc *cheng