-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHASH.c
More file actions
88 lines (77 loc) · 2.18 KB
/
HASH.c
File metadata and controls
88 lines (77 loc) · 2.18 KB
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
84
85
86
87
88
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<stdbool.h>
#define NAME 256
#define SIZE 10
typedef struct person {
char name[NAME];
int age;
//add more information later
}person;
unsigned int hash(char* name) {//collisons occur
/* delt with in two ways open addressing
external chainings */
// liner probing method (just checks for next available hash value)
int length=strnlen(name,NAME);//length comparison
unsigned int hash_value;
for(int i=0;i<length;i++){
hash_value += name[i];//creating a hash value for database
hash_value=(hash_value * name[i]) % SIZE;//creating a hash value for database
}
}
person *hash_table[SIZE];
void ini_hash_table(){//initializing hash table by setting all spaces ot null values
for(int i=0;i<=SIZE;i++){
hash_table[i] = NULL;
}
}
void show(){//print the table
for(int i=0;i<SIZE;i++){
if(hash_table[i] == NULL){
printf("\t%i\t---\n",i);
}else{
printf("\t%i\t%s\n",i,hash_table[i]->name);
}
}
}
bool push(person *p){
if(p==NULL) return false;// condition checking for null pointer
int index=hash(p->name);//index for location in the table to insert a string
if(hash_table[index]!=NULL){//to check if space is available to add str
return false;
}
hash_table[index]=p;//points to the available space
return true;
}
person *srch(char *name){//search a person in the table
int index=hash(name);
if (hash_table[index] !=NULL &&
strncmp(hash_table[index]->name,name,SIZE)==0){
return hash_table[index];
}else{
return NULL;
}
}
person *pop(char *name){
int index=hash(name);
if (hash_table[index] !=NULL &&
strncmp(hash_table[index]->name,name,SIZE)==0){
person *tmp = hash_table[index];
hash_table[index] = NULL;
return tmp;//to free tmp thats allocated on the heap
}else{
return NULL;
}
}
int main(){
ini_hash_table();
person jacob={.name="Jacob",.age=14};
person jack={.name="Jack",.age=24};
person george={.name="George",.age=19};
push(&jacob);
push(&jack);
push(&george);
show();
}