算法导论双重散列

#include
#include
#include

using namespace std;

bool *visited;
int *A;
bool Prime(int x) {
	int y;
	for (y = 2; y <= sqrt(x); y++)
		if (x%y == 0)
			return false;
	return true;
}

//寻找最小素数
int MaxPrime(vector &G) {
	int Max = G.size();
	if (Prime(Max)) {
		return Max;
	}
	else {
		do {
			Max++;
		} while (Prime(Max)==false);
	}
	return Max;
}

//输入数据
void Init(vector &G,int n) {
	int a;
	for (int i = 0; i < n; i++) {
		cin >> a;
		G.push_back(a);
	}
}


int H1(int k, int m) {
	return k%m;
}

int H2(int k, int m) {
	int result = 1 + (k % (m - 1));
	return result;
}


//插入数据
int Hash_Insert(vector &G) {
	int m = MaxPrime(G);
	visited = new bool[m];
	A = new int[m];
	for (int i = 0; i < m; i++) {
		visited[i] = false;
	}

	for (int j = 0; j < G.size(); j++) {
		int locate = H1(G[j], m);
		int locate2 = H2(G[j], m);
		if (visited[locate]==false) {
			A[locate] = G[j];
			visited[locate] = true;
		}
		else {
			do {
				locate = (locate + locate2) % m;
			} while (visited[locate] == true);
		}
	}
	return m;
	
}

int Hash_Search(int k,int m) {
	
	for (int i = 0; i < m; i++) {
		if (A[i] == k) {
			return i;
		}
	}
}

void Delete() {
	delete[]visited;
	delete[]A;
}

int main() {
	vector G;
	int n, k;
	cin >> n;
	Init(G,n);
	int m = Hash_Insert(G);
	cin >> k;
	cout << Hash_Search(k, m) << endl;
	Delete();
	system("pause");
	return 0;
}

你可能感兴趣的:(C++,算法导论)