15A. Hash Table and Function
15A. Hash Table and Function
Code-2
#include<stdio.h>
#define size 7
int arr[size];
void init()
{
int i;
for(i = 0; i < size; i++)
arr[i] = -1;
}
void print()
{
int i;
for(i = 0; i < size; i++)
printf("arr[%d] = %d\n",i,arr[i]);
}
int main()
{
init();
insert(10); //key = 10 % 7 ==> 3
insert(4); //key = 4 % 7 ==> 4
insert(2); //key = 2 % 7 ==> 2
insert(3); //key = 3 % 7 ==> 3 (collision)
printf("Hash table\n");
print();
printf("\n");
return 0;
}
Another code:
CODING-3 for avoiding collision
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 10
// Hash function
unsigned int hash(const char* key)
{
unsigned int hash_value = 0;
int i;
const unsigned int prime = 31;
// Search for a key in the hash table and return its value
int search(HashTable* hash_table, const char* key) {
unsigned int index = hash(key);
Node* node = hash_table->table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return -1; // Key not found
}
Linear Probing
Calculate the hash key. key = data % size;
If hashTable [key] is empty, store the value directly. hashTable [key] = data.
If the hash index already has some value, check for next index.
If the next index is available hashTable[key], store the value. Otherwise try for next index.
#define size 7
struct node
{
int data;
struct node *next;
};
temp->next = newNode;
}
}
void print()
{
int i;
int main()
{
//init array of list to NULL
init();
insert(7);
insert(0);
insert(3);
insert(10);
insert(4);
insert(5);
print();
return 0;
}