【17年扬大真题】分别设计有序表的这把查找(用递归实现)、有序表的折半查找(用非递归实现)的算法。待查找的元素的关键字为整数,用户可由键盘输入表中元素和待查找的元素,要求输入的数据以“0”为结束标志。
//折半查找(递归版)——升序
int Binary_Search2(int arr[], int left, int right,int x) {
int mid = (left + right) / 2;
if (arr[mid] == x) {//递归退出条件
return mid;
}
if (arr[mid] > x) {
//去左半找
return Binary_Search2(arr, left, mid - 1, x);
}
if (arr[mid] < x) {
//去右半找
return Binary_Search2(arr, mid + 1, right, x);
}
}
int main() {
int arr[20];
int n = 0;
printf("请升序输入表中元素个数:");
scanf("%d", &n);
printf("\n");
printf("请输入要表中元素,以0为结束标志:");
int i = 0;
int j = 0;
while (i<n+1) {//输入n个数组元素,再加1个0
int tmp=scanf("%d", &j);
if (tmp == 0) {
break;
}
arr[i] = j;
i++;
}
printf("请输入要查找的元素,将返回给你所需元素的下标:");
int x = 0;
scanf("%d", &x);
int index=Binary_Search2(arr, 0,n-1, x);
printf("所查找元素下标为%d", index);
return 0;
}
//折半查找(非递归版)
int Binary_Search1(int arr[],int length,int x) {
int left = 0;
int right = length - 1;
int mid = 0;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] == x) {
return mid;
}
if (arr[mid] > x) {
right = mid - 1;
}
if (arr[mid] < x) {
left = mid + 1;
}
}
printf("查找失败,请检查是否输入有误!");
return -1;
}
int main() {
int arr[20];
int n = 0;
printf("请升序输入表中元素个数:");
scanf("%d", &n);
printf("\n");
printf("请输入要表中元素,以0为结束标志:");
int i = 0;
int j = 0;
while (i<n+1) {//输入n个数组元素,再加1个0
int tmp=scanf("%d", &j);
if (tmp == 0) {
break;
}
arr[i] = j;
i++;
}
printf("请输入要查找的元素,将返回给你所需元素的下标:");
int x = 0;
scanf("%d", &x);
int index=Binary_Search1(arr, n, x);
printf("所查找元素下标为%d", index);
return 0;
}