用折半查找方法在有序表上查找数据: 用一组有序数据{3,10,17,20,32,43,54,65,76,87}进行验证,当用该源代码查找关键字为20、65时,是否查找成功
时间: 2024-03-25 07:38:08 浏览: 14
采用折半查找和顺序查找来查找某个数
以下是使用折半查找方法在有序表上查找数据的源代码:
```
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
int main() {
int arr[] = {3, 10, 17, 20, 32, 43, 54, 65, 76, 87};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 20;
int result = binarySearch(arr, 0, n - 1, x);
if(result == -1)
printf("Element is not present in array");
else
printf("Element is present at index %d", result);
x = 65;
result = binarySearch(arr, 0, n - 1, x);
if(result == -1)
printf("\nElement is not present in array");
else
printf("\nElement is present at index %d", result);
return 0;
}
```
根据上述代码,在给定的有序数据中,当查找关键字为20时,查找成功,并返回元素的下标为3;当查找关键字为65时,查找也成功,并返回元素的下标为7。
阅读全文