I'm having problems with hashing. Don't mind the rehashing. Don't mind the "2" in hashfile.txt. a[m] values start with array[1] which is 13.
My problem is that [13]->13, -721924 it prints unnecessary numbers and does segmentation fault afterwards. it should only be [13]->13 and the array is upto [16]->.
hash.c
Code:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int x;
struct Node *next;
}node;
void display(node *a[], int m){
int i;
for(i=0; i<m; i++){
printf("[%d]->", i);
while(a[i]!=NULL){
printf("%d, ", a[i]->x);
a[i]=a[i]->next;
}
printf("\n");
}
}
void open(node *a[], int m, int array[]){
int i, index;
for(i=0; i<m; i++)
a[i]==NULL;
for(i=0; i<array[1]; i++){
index= array[1+i+1]%m;
node *temp=malloc(sizeof(node ));
temp->x = array[1+i+1];
node *temp2;
temp2= a[index];
temp->next = NULL;
a[index] = temp;
a[index]->next = temp2;
}
display(a, m);
}
void linear(node *a[], int m, int array[]){
int i, index;
for(i=0; i<m; i++)
a[i]==NULL;
for(i=0; i<array[1]; i++){
int j=0;
do{
index= ((array[1+i+1]%m)+j)%m;
if(a[index]!=NULL)
j++;
}while(a[index]!=NULL);
j=0;
node *temp=malloc(sizeof(node ));
temp->x = array[1+i+1];
node *temp2;
temp2= a[index];
temp->next = NULL;
a[index] = temp;
a[index]->next = temp2;
}
display(a, m);
}
void quadratic(node *a[], int m, int array[]){
int i, index;
for(i=0; i<m; i++)
a[i]==NULL;
for(i=0; i<array[1]; i++){
int j=0;
do{
index= ((array[1+i+1]%m)+(j*j))%m;
if(a[index]!=NULL)
j++;
}while(a[index]!=NULL);
j=0;
node *temp=malloc(sizeof(node ));
temp->x = array[1+i+1];
node *temp2;
temp2= a[index];
temp->next = NULL;
a[index] = temp;
a[index]->next = temp2;
}
display(a, m);
}
void double(node *a[], int m, int array[]){
int index;
for(i=0; i<array[0]; i++)
a[i]==NULL;
for(i=0; i<array[1]; i++){
int j=0;
do{
index= ((array[1+i+1]%m)+(j*(5-(array[1+i+1]%5))))%m;
if(a[index]!=NULL)
j++;
}while(a[index]!=NULL);
j=0;
node *temp=malloc(sizeof(node ));
temp->x = array[1+i+1];
node *temp2;
temp2= a[index];
temp->next = NULL;
a[index] = temp;
a[index]->next = temp2;
}
display(a, m);
}
main() {
FILE *fp = fopen("hashfile.txt", "r");
int array[100];
int i;
for (i = 0; i < 100; i++) {
fscanf(fp, "%d", &array[i]);
}
fclose(fp);
int m;
m= (array[1]*2)+1;
node **a=malloc(sizeof(node *)*m);
printf("Open Hashing\n");
open(a, m, array);
printf("Closed Hashing\n");
printf("(Linear Probing)\n");
linear(a, m, array);
printf("(Quadratic Probing)\n");
quadratic(a, m, array);
printf("(Double Hashing)\n");
double(a, m, array);
}
hashfile.txt
2
8
13
21
23
15
6
1
3
56