C Program to Implement Hash Tables with Quadratic Probing

This is a C program to Implement Hash Tables with Quadratic Probing.

Problem Description

A hash table is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots. Quadratic Probing is similar to Linear Probing. The difference is that if we to try to insert into a space that is filled we would first check 1^1=1 element away then 2^2=4 elements away, then 3^2=9 elements away then 4^2=16 elements away and so on.

Problem Solution

1. Create an array of structure (i.e a hash table).
2. Take a key and a value to be stored in hash table as input.
3. Corresponding to the key, an index will be generated i.e every key is stored in a particular array index.
4. Using the generated index, access the data located in that array index.
5. In case of absence of data, create one and insert the data item (key and value) into it and increment the size of hash table.
6. In case the data exists, probe through the subsequent elements (looping back if necessary) for free space to insert new data item.
Note: This probing will continue until we reach the same element again (from where we began probing)
Note: Here, unlike Linear Probing, probing will be done according to the following formula –
(currentPosition + h) % arraySize => Linear Probing
(currentPosition + (h * h)) % arraySize => Quadratic Probing
where h = 1, 2, 3, 4 and so on.
7. To display all the elements of hash table, element at each index is accessed (via for loop).
8. To remove a key from hash table, we will first calculate its index and delete it if key matches, else probe through elements until we find key or an empty space where not a single data has been entered (means data does not exist in the hash table).
9. Exit

Program/Source Code

Here is the source code of the C Program to implement a Hash Table with Quadratic Probing. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. /* to store a data (consisting of key and value) in hash table array */
  5. struct item 
  6. {
  7. 	int key;
  8. 	int value;
  9. };
  10.  
  11. /* each hash table item has a flag (status) and data (consisting of key and value) */
  12. struct hashtable_item 
  13. {
  14.  
  15. 	int flag;
  16. 	/*
  17. 	 * flag = 0 : data does not exist
  18. 	 * flag = 1 : data exists at given array location
  19. 	 * flag = 2 : data was present at least once
  20. 	*/
  21. 	struct item *data;
  22.  
  23. };
  24.  
  25. struct hashtable_item *array;
  26. int size = 0;
  27. int max = 10;
  28.  
  29. /* this function returns corresponding index of the given key */
  30. int hashcode(int key)
  31. {
  32. 	return (key % max);
  33. }
  34.  
  35. /* this  function initializes the hash table array */
  36. void init_array()
  37. {
  38. 	int i;
  39. 	for (i = 0; i < max; i++) 
  40.         {
  41. 		array[i].flag = 0;
  42. 		array[i].data = NULL;
  43. 	}
  44. }
  45.  
  46. /* this function inserts an element in the hash table */
  47. void insert(int key, int value)
  48. {
  49. 	int index = hashcode(key);
  50.  
  51. 	int i = index;
  52. 	int h = 1;
  53.  
  54. 	struct item *new_item = (struct item*) malloc(sizeof(struct item));
  55. 	new_item->key = key;
  56. 	new_item->value = value;
  57.  
  58. 	/* probing through the array until an empty space is found */
  59. 	while (array[i].flag == 1) 
  60.         {
  61.  
  62. 		if (array[i].data->key == key) 
  63.                 {
  64.  
  65. 			/* case when already present key matches the given key */
  66. 			printf("\n This key is already present in hash table, hence updating it's value \n");
  67. 			array[i].data->value = value;
  68. 			return;
  69.  
  70. 		}
  71. 		i = (i + (h * h)) % max;
  72. 		h++;
  73. 		if (i == index)
  74.                 {
  75. 			printf("\n Hash table is full, cannot add more elements \n");
  76. 			return;
  77. 		}
  78.  
  79. 	}
  80.  
  81. 	array[i].flag = 1;
  82. 	array[i].data = new_item;
  83. 	printf("\n Key (%d) has been inserted\n", key);
  84. 	size++;
  85.  
  86. }
  87.  
  88. /* to remove an element form the hash table array */
  89. void remove_element(int key)
  90. {
  91. 	int index = hashcode(key);
  92. 	int i = index;
  93. 	int h = 1;
  94.  
  95. 	/* probing through the hash table until we reach at location where there had not been an element even once */
  96. 	while (array[i].flag != 0)
  97.         {
  98. 		if (array[i].flag == 1  &&  array[i].data->key == key) 
  99.                 {
  100.  
  101. 			/* case where data exists at the location and its key matches to the given key */
  102. 			array[i].flag = 2;
  103. 			array[i].data = NULL;
  104. 			size--;
  105. 			printf("\n Key (%d) has been removed \n", key);
  106. 			return;
  107.  
  108. 		}
  109. 		i = (i + (h * h)) % max;
  110. 		h++;
  111. 		if (i == index) 
  112.                 {
  113. 			break;
  114. 		}
  115. 	}
  116. 	printf("\n Key does not exist \n");
  117.  
  118. }
  119.  
  120. /* to display the contents of hash table */
  121. void display()
  122. {
  123.  
  124. 	int i;
  125. 	for(i = 0; i < max; i++)
  126.         {
  127. 		if (array[i].flag != 1)
  128.                 {
  129. 			printf("\n Array[%d] has no elements \n", i);
  130. 		}
  131. 		else
  132.                 {
  133. 			printf("\n Array[%d] has elements \n  %d (key) and %d (value) \n", i, array[i].data->key, array[i].data->value);
  134. 		}
  135. 	}
  136.  
  137. }
  138.  
  139. int size_of_hashtable()
  140. {
  141. 	return size;
  142. }
  143.  
  144. void main()
  145. {
  146. 	int choice, key, value, n, c;
  147. 	clrscr();
  148.  
  149. 	array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));
  150. 	init_array();
  151.  
  152. 	do {
  153. 		printf("Implementation of Hash Table in C with Quadratic Probing.\n\n");
  154. 		printf("MENU-: \n1.Inserting item in the Hash table" 
  155.                               "\n2.Removing item from the Hash table" 
  156.                               "\n3.Check the size of Hash table" 
  157.                               "\n4.Display Hash table"
  158. 		       "\n\n Please enter your choice-:");
  159.  
  160. 		scanf("%d", &choice);
  161.  
  162. 		switch(choice)
  163.                 {
  164.  
  165. 		case 1:
  166.  
  167. 		      printf("Inserting element in Hash table \n");
  168. 		      printf("Enter key and value-:\t");
  169. 		      scanf("%d %d", &key, &value);
  170. 		      insert(key, value);
  171.  
  172. 		      break;
  173.  
  174. 		case 2:
  175.  
  176. 		      printf("Deleting in Hash table \n Enter the key to delete-:");
  177. 		      scanf("%d", &key);
  178. 		      remove_element(key);
  179.  
  180. 		      break;
  181.  
  182. 		case 3:
  183.  
  184. 		      n = size_of_hashtable();
  185. 		      printf("Size of Hash table is-:%d\n", n);
  186.  
  187. 		      break;
  188.  
  189. 		case 4:
  190.  
  191. 		      display();
  192.  
  193. 		      break;
  194.  
  195. 		default:
  196.  
  197. 		       printf("Wrong Input\n");
  198.  
  199. 		}
  200.  
  201. 		printf("\n Do you want to continue-:(press 1 for yes)\t");
  202. 		scanf("%d", &c);
  203.  
  204. 	}while(c == 1);
  205.  
  206. 	getch();
  207.  
  208. }
Program Explanation

Note : Hash table with Linear Probing runs the same way as Hash table with Quadratic Probing except that in case of data collision, next position in Quadratic Probing is calculated as -:
(currentPosition + (h * h)) % arraySize, where h = 1, 2, 3, 4……
whereas in Linear Probing the formula used is -:
(currentPosition + h) % arraySize, where h = 1, 2, 3, 4……..

advertisement
advertisement

1. Create a structure, item having a key and value representing data to be inserted in hash table.
2. Create another structure, hash table_item with variable data (key and value) and flag as a status variable which informs about the status of array index.
flag = 1 : presence of some data at the array index.
flag = 0 : data not present in array index even once
flag = 2 : data had been removed from array index at least once
3. Now create an array of structure (hashtable_item) of some certain size(10, in this case). This array will be our hash table.
4. A menu is displayed on the screen.
5. User must choose one option from four choices given in the menu.
6. 1st choice: Inserting item into hash table
(a) Take a key and a value as input.
(b) Calculate index as per the given key (using hashcode() function).
(c) Access the element at this calculated index in array.
(d) If there is no element at that particular array index, add straight way.
(e) If an element is present, check whether the given key matches the element’s key. If yes, then update it’s value and return. Otherwise probe through subsequent elements (looping back if necessary), to find free space. While probing
* if given key matches the element’s key, update its value and return.
* if a free space is found, add the data at that position.
Probing will stop until we reach the same element from where we began probing. Until then, if no free space is found, then add will fail.
7. 2nd choice: Removing a key from hash table
(a) Take a key as input which needs to be removed.
(b) Calculate index as per the given key (using hashcode() function).
(c) Access the element at the calculated array index.
(d) If an element is present, check whether the given key matches the element’s key. If yes, then delete the key and return decrementing the size. Otherwise probe through subsequent elements (looping back if necessary), to find free space with flag = 0. While probing
* if given key matches the element’s key, delete and return.
* if a free space is found (with flag = 2), continue to probe.
(e) If no free space (flag = 0) is found even after probing through all element it means, key does not exist in the hash table.
8. 3rd choice: Size of hash table
(a) Each time we add a new data item into the hash table, we increment it’s size by 1.
(b) Each time we remove a data item from the hash table, we decrement it’s size by 1.
(c) The size of the hash table can be determined either by size variable or size_of_hashtable() method.

9. 4th choice: Display hash table
(a) Function display() runs for displaying hash table contents.
(b) Here a for loop runs from 0 to array_size-1 with i as iterator.
(c) The code inside loop consists of taking i as index and accessing each element at that index of array.

Runtime Test Cases
 
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 3
Size of hash table is-: 0
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 1
Inserting element in Hash table
Enter key and value-:   12 	10
 
 Key (12) has been inserted
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 1
Inserting element in hash table
Enter key and value-:   122 	4
 
 Key (122) has been inserted
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 1
Inserting element in hash table
Enter key and value-:   82 	5
 
 Key (82) has been inserted
 
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 3
Size of hash table is-: 3
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 4
Array[0] has  no elements
 
Array[1] has no elements
 
Array[2] has elements-:
12 (key) and 10 (value)
 
Array[3] has elements-:
122(key) and 4(value)
 
Array[4] has no elements
 
Array[5] has no elements
 
Array[6] has no elements
 
Array[7] has no elements
82(key) and 5(value)
Array[8] has no elements
 
Array[9] has no elements
 
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 2
Deleting in hash table
Enter the key to delete-: 122
 
 Key (122) has been removed
 
Do you want to continue-:(press 1 for yes) 1
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
 
Please enter your choice-: 2
Deleting in hash table
Enter the key to delete-: 56
 
 This key does not exist
 
Do you want to continue-:(press 1 for yes) 2

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.