请用c一眼实现简单有序表的二分(折半)查找。从键盘输入N (N<20)个值建立有序表,然后进行二分查找,查找某个元素值。
时间: 2023-07-19 13:04:10 浏览: 63
以下是使用 C 语言实现简单有序表的二分查找的代码:
```c
#include <stdio.h>
int binarySearch(int arr[], int n, int x) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
}
else if (arr[mid] < x) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
int main() {
int n, arr[20], x;
printf("Enter the number of elements in the array (N < 20): ");
scanf("%d", &n);
printf("Enter the elements of the array in ascending order: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the element to search: ");
scanf("%d", &x);
int index = binarySearch(arr, n, x);
if (index == -1) {
printf("Element not found in the array.\n");
}
else {
printf("Element found at index %d in the array.\n", index);
}
return 0;
}
```
程序首先从键盘读取 N 个值,然后将它们存储在一个数组中。然后,它从键盘读取要查找的元素值,并使用二分查找算法在数组中查找该元素。如果元素存在于数组中,则程序打印该元素的索引;否则,程序打印“元素在数组中未找到”。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)