Create a Hash Table to store numbers. Also, search numbers in that Hash Table. Write Code in C
define _CRT_SECURE_NO_WARNINGS
include
include
include
define MaxNumbers 50
// to divide with
define N 100
define Empty 0
define STORAGESIZE 100
int hashTable[STORAGESIZE + 1];
//initialize hash table
void initializeHashTable() {
for (int counter = 0; counter < STORAGESIZE; counter++) {
hashTable[counter] = 0;
}
}
//find a number and return found/not-found
int searchHashTable(int numberToFind) {
int hashSearchPosition = numberToFind % N + 1;
if (hashTable[hashSearchPosition] == numberToFind) {
printf("%d %s %d", numberToFind, " Found at ", hashSearchPosition );
return 1;
}
else {
for (int pos = hashSearchPosition + 1; pos < STORAGESIZE; pos++) {
if (hashTable[pos] == numberToFind) {
printf("%d %s %d", numberToFind, " Found at ", pos);
return 1;
}
}
}
printf("Number Not Found");
return -1;
}
//find next position after a collission
int findNextAvailablePosition(int index) {
for (int pos = index + 1; pos < STORAGESIZE; pos++) {
if (hashTable[pos] == 0) {
return pos;
}
}
return -1;
}
//insert data into hash table
int insertToHashTable(int l_numberToInsert) {
int hashPosition = l_numberToInsert % N + 1;
if ( hashTable[hashPosition] > 0) {
//collision
//so find the next position
hashPosition = findNextAvailablePosition(hashPosition);
}
//error finding a position
if ( (hashPosition >= STORAGESIZE) || ((hashPosition == -1)) ) {
// indicates error
return -1;
}
hashTable[hashPosition] = l_numberToInsert;
// 1 indicates success
return 1;
}
//flow of the work
int main() {
//initialize
initializeHashTable();
//read data from file
FILE *in = fopen("input.txt", "r");
int numberToInsert = 0;
//convertWordToNumber()
//insertion
//insert data into the hash table
while ( fscanf(in, "%d", &numberToInsert) == 1 ) {
insertToHashTable(numberToInsert);
}
//take input from user to search
printf("\n%s\n", "Give a number to search");
int numberToSearch = 56;
scanf("%d", &numberToSearch);
//find the number in the hash
searchHashTable(numberToSearch);
}