# 确定性算法A查找链表中的x下标

ch11.ppt P59

``````
#include "pch.h"
#include <iostream>
#include <random>
#include <vector>
#include <ctime>
#include <algorithm>
#define MAXN 10000
using namespace std;
//产生一个随机数组val
vector<int> getVector() {
vector<int> v;
uniform_int_distribution<unsigned> u(1, 1000);
default_random_engine e(time(0));
for (auto i = 1; i <=10; ++i)
v.push_back(u(e));
return v;

}
//打印数组
void print(vector<int> v) {
for (auto i : v)
cout << i << " ";
cout << endl;
}
//生成数组ptr[]
vector<int> getPtr(vector<int> val) {
vector<int> ptr(val.size(),-1);
auto min_it = min_element(val.begin(), val.end());
int pos = min_it-val.begin();
while (*min_it != MAXN) {
*min_it = MAXN;

pos = min_it - val.begin();

min_it = min_element(val.begin(), val.end());

ptr[pos] = min_it - val.begin();

}
return ptr;
}
//查找x在数组val的下标
int Search(int x, int i,vector<int> val,vector<int> ptr) {
while (x > val[i])
i = ptr[i];
return i;
}
//算法A(x)，在表val中查找x的下标
int A(int x, vector<int> val, vector<int> ptr) {
int head = min_element(val.begin(), val.end()) - val.begin();
}
int main() {
vector<int> val = {2,3,13,1,5,21,8};

vector<int> ptr = getPtr(val);
print(val);

cout << A(8, val, ptr) << endl;

}``````

;