算法导论11.4开放寻址法(除法哈希函数开放寻址处理冲突)

image

9CE0DSYQJA5V]5604XBXL)O

ASFVQ{T3E9I4SBQK{4JZ%Y5

/*
 * IA_11.4OpenAddressing.h
 *
 *  Created on: Feb 13, 2015
 *      Author: sunyj
 */

#ifndef IA_11_4OPENADDRESSING_H_
#define IA_11_4OPENADDRESSING_H_

#include <stdint.h>
#include <string.h>
#include <iostream>
class Node {
public:
	Node() { }
	Node(int64_t const k, int64_t const d) : key(k), data(d) { }
	int64_t key;
	int64_t data;
};

class OpenAddressingLinerProb {

public:
	OpenAddressingLinerProb(int64_t const n) : length(n)
	{
		data = new Node[n]();
		memset(data, -1, n * sizeof(Node));
	}
	int64_t HashFunc(int64_t const key)
	{
		return key % length;
	}
	Node HashFuncLinerProbSearch(int64_t const key)
	{
		for (int64_t i = 0; i < length; i++)
		{
			if (data[HashFunc(key) + i].key == key)
			{
				return data[HashFunc(key) + i];
			}
		}
		return Node();
	}
	void HashFuncLinerProbInsert(Node const x)
	{
		for (int64_t i = 0; i < length; i++)
		{
			if (data[HashFunc(x.key) + i].key == -1)
			{
				data[HashFunc(x.key) + i] = x;
				return ;
			}
		}
	}
private:
	Node*   data;
	int64_t length;
};

#endif /* IA_11_4OPENADDRESSING_H_ */
/*
 * IA_11.4OpenAddressing.cpp
 *
 *  Created on: Feb 12, 2015
 *      Author: sunyj
 */

#include "IA_11.4OpenAddressing.h"

int main()
{
	OpenAddressingLinerProb linertable(7);
	Node node2(2, 200);
	Node node3(5, 300);
	Node node9(9, 900);
	Node node4(4, 400);

	linertable.HashFuncLinerProbInsert(node2);
	linertable.HashFuncLinerProbInsert(node3);
	linertable.HashFuncLinerProbInsert(node9);
	linertable.HashFuncLinerProbInsert(node4);

	Node tmp = linertable.HashFuncLinerProbSearch(4);
	std::cout << tmp.data << std::endl;
	tmp = linertable.HashFuncLinerProbSearch(2);
	std::cout << tmp.data << std::endl;
	tmp = linertable.HashFuncLinerProbSearch(9);
	std::cout << tmp.data << std::endl;
	return 0;
}

// Linear probing
 
 

99ddd96b18c1e4fd73533e1562c1f37a131a68cdb61fceb569b924f006c749f5148d9933d60bdfdb9abb897bf9bd5ee8149f6d1ace7bfca72de0ac29cfaece60198b2dc293aba48454c93f5a8b0c3e6c254c320140629d43311c8ba038edcc15334d8bf58490a58359b033b5bb5c9ea4dd2cbfcd739b6003af3b388

原文地址:https://www.cnblogs.com/sunyongjie1984/p/4288415.html