
Реализации различных алгоритмов на Си / хеширование
.doc
-
Листинг программы
Хеширование
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <locale.h>
#include <time.h>
struct dann{
int key;
float mas[5];
char str[20];
};
struct dann* vvod_dann(int *N)
{
int i;
struct dann *A;
printf("Введите количество элементов в информационном массиве: ");
scanf("%d",N);
A=(struct dann*)malloc(*N*sizeof(struct dann));
srand((unsigned)time(NULL));
for(i=0;i<*N;i++)
{
for(int j=0;j<5;j++)
A[i].mas[j]=(float)rand()/100;
printf("Введите ключ %d: ",i);
scanf("%d", &A[i].key);
printf("Введите строку %d: ",i);
scanf("%s", &A[i].str);
}
return A;
}
int** hesh(struct dann *A,int N)
{
int **hesh_tabl,p;
hesh_tabl=(int**)malloc(1000*sizeof(int*));
for(int i=0;i<1000;i++)
{
hesh_tabl[i]=(int*)malloc(2*sizeof(int));
hesh_tabl[i][0]=0;
hesh_tabl[i][1]=0;
}
for(int i=0;i<N;i++)
{
p=A[i].key%1000;
if(hesh_tabl[p][0]==0)
{
hesh_tabl[p][0]=A[i].key;
hesh_tabl[p][1]=i;
}
else
{
while((hesh_tabl[p][0])!=0)
p++;
hesh_tabl[p][0]=A[i].key;
hesh_tabl[p][1]=i;
}
}
return hesh_tabl;
}
void find(struct dann *A, int **tabl, int N)
{
int key,p=0,k;
printf("Введите искомое значение: ");
scanf("%d",&key);
k=key%1000;
if(tabl[k][0]==key)
p=1;
else
{
while(tabl[k][0]!=key)
k++;
p=1;
}
if(p==1)
{
for(int i=0;i<5;i++)
printf("\nInf_mas[%d].mas[%d]=%f",tabl[k][1],i,A[tabl[k][1]].mas[i]);
printf("\n%s",A[tabl[k][1]].str);
}
}
void main()
{
setlocale(LC_ALL,"Rus");
int **hesh_tabl,N,i,j;
struct dann *Inf_mas;
Inf_mas=vvod_dann(&N);
hesh_tabl=hesh(Inf_mas,N);
for(i=0;i<N;i++)
{
for(j=0;j<5;j++)
printf("%f *|* ",Inf_mas[i].mas[j]);
printf("\nInf_mas[%d].key= %d\n\n",i,Inf_mas[i].key);
}
find(Inf_mas,hesh_tabl,N);
getch();
}