更新 'ex7_1.c'

This commit is contained in:
xtaodada 2022-05-26 14:38:08 +00:00
parent 23c8f197fc
commit eeac176312

70
ex7_1.c
View File

@ -30,12 +30,77 @@ void Search2(int a[], int n, int key){
} }
printf("\n未找到。\n\n"); printf("\n未找到。\n\n");
} }
void InitHashList(int b[]){
int i;
for (i = 0; i < MAX; i++)
b[i] = 0;
}
int Hash(int key){
return (key * 3) % 7;
}
int Insert(int a[], int b[], int e){
int d = Hash(e);
int temp = d;
while (b[d] != 0){
d = (d + 1) % 7;
if (d == temp){
printf("散列表已满\n");
return 0;
}
}
a[d] = e;
b[d] = 1;
return 1;
}
int Search3(int a[], int b[], int key){
int d = Hash(key);
int temp = d;
int p = b[d];
while (p != 0){
if (a[d] == key){
return d;
} else {
d = (d + 1) % 7;
p = b[d];
}
if(temp == d){
break;
}
}
return -1;
}
void start_hash(int a[], int b[]){
int n, e;
InitHashList(a);
InitHashList(b);
printf("请输入需要输入的元素个数:");
scanf("%d",&n);
for(int i=0; i<n; i++){
printf("请输入第 %d 个元素:", i+1);
scanf("%d", &e);
Insert(a, b, e);
}
printf("\n散列表为:");
for(int i=0; i<7; i++){
printf("%d ", a[i]);
}
printf("\n");
printf("\n请输入需要查找的元素:");
scanf("%d", &e);
n = Search3(a, b, e);
if(n != -1){
printf("\n此数在第 %d 位。\n\n", n + 1);
} else {
printf("\n未找到。\n\n");
}
}
int main(){ int main(){
int n, choice, e, a[MAX]; int n, choice, e, a[MAX], b[MAX];
for(;;){ for(;;){
printf("\t\t1.无序线性表的顺序查找\n"); printf("\t\t1.无序线性表的顺序查找\n");
printf("\t\t2.有序线性表的二分查找\n"); printf("\t\t2.有序线性表的二分查找\n");
printf("\t\t3.利用散列表实现查找\n");
printf("\t\t0.退出\n"); printf("\t\t0.退出\n");
printf("请选择:"); printf("请选择:");
@ -66,6 +131,9 @@ int main(){
scanf("%d",&e); scanf("%d",&e);
Search1(a, n, e); Search1(a, n, e);
break; break;
case 3:
start_hash(a, b);
break;
default: default:
break; break;
} }