79 lines
1.5 KiB
C
79 lines
1.5 KiB
C
#include<stdio.h>
|
|
#include<stdlib.h>
|
|
#include<conio.h>
|
|
#define MAX 100
|
|
|
|
void Search1(int a[], int n, int key){
|
|
int i=0;
|
|
a[n] = key;
|
|
while(a[i] != key){
|
|
i++;
|
|
}
|
|
if(i == n){
|
|
printf("\n未找到。\n\n");
|
|
} else {
|
|
printf("\n此数在第 %d 位。\n\n", i + 1);
|
|
}
|
|
}
|
|
void Search2(int a[], int n, int key){
|
|
int low = 0, high = n-1, mid;
|
|
while(low <= high){
|
|
mid = (low + high) / 2;
|
|
if(a[mid] == key){
|
|
printf("\n此数在第 %d 位。\n\n", mid + 1);
|
|
return;
|
|
} else if (a[mid] > key){
|
|
high = mid - 1;
|
|
} else {
|
|
low = mid + 1;
|
|
}
|
|
}
|
|
printf("\n未找到。\n\n");
|
|
}
|
|
int main(){
|
|
int n, choice, e, a[MAX];
|
|
|
|
for(;;){
|
|
printf("\t\t1.无序线性表的顺序查找\n");
|
|
printf("\t\t2.有序线性表的二分查找\n");
|
|
printf("\t\t0.退出\n");
|
|
|
|
printf("请选择:");
|
|
scanf("%d",&choice);
|
|
if(choice==0) break;
|
|
switch (choice) {
|
|
case 1:
|
|
printf("请输入需要输入的元素个数:");
|
|
scanf("%d",&n);
|
|
for(int i=0;i<n;i++){
|
|
printf("请输入第 %d 个元素:",i+1);
|
|
scanf("%d",&e);
|
|
a[i] = e;
|
|
}
|
|
printf("\n请输入需要查找的元素:");
|
|
scanf("%d",&e);
|
|
Search1(a, n, e);
|
|
break;
|
|
case 2:
|
|
printf("请输入需要输入的元素个数:");
|
|
scanf("%d",&n);
|
|
for(int i=0;i<n;i++){
|
|
printf("请输入第 %d 个元素:",i+1);
|
|
scanf("%d",&e);
|
|
a[i] = e;
|
|
}
|
|
printf("\n请输入需要查找的元素:");
|
|
scanf("%d",&e);
|
|
Search1(a, n, e);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
printf("请按任意键继续...");
|
|
getch();
|
|
system("cls");
|
|
}
|
|
printf("感谢使用,再见\n");
|
|
return 0;
|
|
}
|