TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
hash_search.cpp
Go to the documentation of this file.
1
18#include <cstdlib>
19#include <iostream>
20
21#define MAX 6
22#define HASHMAX 5
23
24int data[MAX] = {1, 10, 15, 5, 8, 7};
25
29typedef struct list {
30 int key;
31 struct list* next;
34
36
37// int counter = 1;
38
45int h(int key) { return key % HASHMAX; }
46
55void create_list(int key) { // Construct hash table
56 link p, n;
57 int index;
58 n = (link)malloc(sizeof(node));
59 n->key = key;
60 n->next = NULL;
61 index = h(key);
62 p = hashtab[index].next;
63 if (p != NULL) {
64 n->next = p;
65 hashtab[index].next = n;
66 } else {
67 hashtab[index].next = n;
68 }
69}
70
76int hash_search(int key, int* counter) { // Hash lookup function
77 link pointer;
78 int index;
79
80 *counter = 0;
81 index = h(key);
82 pointer = hashtab[index].next;
83
84 std::cout << "data[" << index << "]:";
85
86 while (pointer != NULL) {
87 counter[0]++;
88 std::cout << "data[" << pointer->key << "]:";
89 if (pointer->key == key)
90 return 1;
91 else
92 pointer = pointer->next;
93 }
94
95 return 0;
96}
97
99int main() {
100 link p;
101 int key, index, i, counter; // Key is the value to be found
102 index = 0;
103
104 // You can write the input mode here
105 while (index < MAX) { // Construct hash table
106 create_list(data[index]);
107 index++;
108 }
109
110 for (i = 0; i < HASHMAX; i++) { // Output hash table
111 std::cout << "hashtab [" << i << "]\n";
112
113 p = hashtab[i].next;
114
115 while (p != NULL) {
116 std::cout << "please int key:";
117 if (p->key > 0)
118 std::cout << "[" << p->key << "]";
119 p = p->next;
120 }
121 std::cout << std::endl;
122 }
123
124 while (key != -1) {
125 // You can write the input mode here
126 // test key = 10
127 key = 10;
128 if (hash_search(key, &counter))
129 std::cout << "search time = " << counter << std::endl;
130 else
131 std::cout << "no found!\n";
132 key = -1; // Exit test
133 /* The test sample is returned as:
134 * data[0]:data[5]:data[15]:data[10]:search time = 3 The search is
135 * successful. There are 10 in this set of data */
136 }
137
138 return 0;
139}
int hash_search(int key, int *counter)
#define MAX
Determines how much data.
int h(int key)
int data[MAX]
test data
#define HASHMAX
Determines the length of the hash table.
struct list node
void create_list(int key)
struct list * link
pointer to nodes
int main()
node hashtab[HASHMAX]
array of nodes
struct list * next
pointer to next link in the chain
int key
key value for node