-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathVishruthS_Q27_Hashing1.c
83 lines (71 loc) · 2.06 KB
/
VishruthS_Q27_Hashing1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//CSL201 DATA STRUCTURES LAB ----- VISHRUTH S, CS3A, 61
//CYCLE 4 QUESTION 1
//To insert a set of keys into a hash table of size m=13 using the division method and the collision resolution technique as linear probing.
#include <stdio.h>
#define SIZE 13
// Initializing hash table with zeroes
int hashTable[SIZE] = {0};
// ========== HASHING FUNCTION ========= //
void performHash(int inputArr[], int inputSize)
{
int key;
for (int i = 0; i < inputSize; i++) // for every element in input array
{
key = inputArr[i] % SIZE; // Finding index using the mod function
if (hashTable[key] == 0) // If empty
hashTable[key] = inputArr[i]; //then just insert in that index
else
{
int j;
j = (key + 1) % SIZE; // else find the next index
while (1) // Repeat till an empty index is found
{
if (hashTable[j] == 0) // check if it is empty
{
hashTable[j] = inputArr[i]; //then insert
break; //and exit out of loop
}
else
{
j = (j + 1) % SIZE; // else go to next index
}
}
}
}
}
void printHashTable();
// Main function
int main()
{
int inputArr[SIZE];
int inputSize;
printf("Enter size of input array\n");
scanf("%d", &inputSize);
if (inputSize > SIZE)
{
printf("\nSorry, Max size exceeded");
return 0;
}
printf("Enter elements\n");
for (int i = 0; i < inputSize; i++)
scanf("%d", &inputArr[i]);
performHash(inputArr, inputSize);
printHashTable();
return 0;
}
// To print the result hash table
void printHashTable()
{
printf("\nHash table");
printf("\nIndex:\t");
for (int i = 0; i < SIZE; i++)
{
printf("%d\t", i);
}
printf("\nValue:\t");
for (int i = 0; i < SIZE; i++)
{
hashTable[i] != 0 ? printf("%d\t", hashTable[i]) : printf("__\t");
}
printf("\n");
}