修改折半查找算法使之能够进行范围查找,找出在给定值a和b之间的元素C语言代码
时间: 2024-05-03 12:22:19 浏览: 25
以下是修改后的折半查找算法,能够进行范围查找:
```
int binarySearchRange(int arr[], int n, int a, int b) {
int low = 0, high = n - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] >= a && arr[mid] <= b) {
return mid;
} else if (arr[mid] < a) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // 没有找到在给定范围内的元素
}
void binarySearchRangeResult(int arr[], int n, int a, int b) {
int firstIndex = binarySearchRange(arr, n, a, b);
if (firstIndex == -1) {
printf("没有找到在给定范围内的元素");
return;
}
printf("在给定范围内的元素为: ");
int lastIndex = firstIndex;
while (lastIndex < n && arr[lastIndex] <= b) {
printf("%d ", arr[lastIndex]);
lastIndex++;
}
}
```
该算法的实现方式与普通的折半查找算法类似,不同之处在于在找到一个符合条件的元素后,需要继续向后查找,直到找到不符合条件的元素为止,这样就能找到在给定范围内的所有元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)