借助于快速排序的算法思想,在一组无序的记录中查找给定关键字值等于key的记录,设此组记录存放于数组r[1…n]中。若查找成功,则返回该记录在r数组中的位置,否则显示“not find”信息。
源代码如下
#include <iostream>
#include <vector>
using namespace std;
int find(vector<int> & records, int key)
{
int i=0;
int j = records.size() - 1;
while(i<j)
{
while(i<j && records[i] <key) i++;
if(records[i] == key) return i; else i++;
while(i<j && records[j] >key) j--;
if(records[j] == key) return j; else j--;
}
return - 1;
}
int main()
{
vector<int> records = {7,8,-7,0,-3,6,1,-9,0,4,-4,2};
int pos = find(records, 2);
if(pos == -1)
{
cout << "not find" <<endl;
}
else
{
cout << (pos) <<endl;
}
for (auto& record : records)
{
cout << record <<"";
}
return 0;
}
运行结果: