生成一段折半查找的c语言代码
时间: 2023-11-19 19:05:28 浏览: 91
好的,这是一段实现折半查找的C语言代码:
```c
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
```
这段代码使用了while循环进行迭代,每次计算中间值mid,并比较arr[mid]与要查找的值x的大小关系,不断更新左右边界l和r,最终返回查找结果。
相关问题
生成一组随机数,然后编写堆排序算法实现数据排序,并以折半查找算法实现任意某值的查找C语言描述
以下是生成一组随机数的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 10
int main() {
int nums[MAX_NUM];
int i;
srand(time(NULL));
for (i = 0; i < MAX_NUM; i++) {
nums[i] = rand() % 100;
printf("%d ", nums[i]);
}
return 0;
}
```
接下来是堆排序算法的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 10
void heapify(int *nums, int i, int n) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && nums[left] > nums[largest]) {
largest = left;
}
if (right < n && nums[right] > nums[largest]) {
largest = right;
}
if (largest != i) {
int tmp = nums[i];
nums[i] = nums[largest];
nums[largest] = tmp;
heapify(nums, largest, n);
}
}
void heap_sort(int *nums, int n) {
int i;
for (i = n / 2 - 1; i >= 0; i--) {
heapify(nums, i, n);
}
for (i = n - 1; i >= 0; i--) {
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
heapify(nums, 0, i);
}
}
int binary_search(int *nums, int n, int target) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int main() {
int nums[MAX_NUM];
int i;
srand(time(NULL));
for (i = 0; i < MAX_NUM; i++) {
nums[i] = rand() % 100;
printf("%d ", nums[i]);
}
heap_sort(nums, MAX_NUM);
printf("\nSorted:\n");
for (i = 0; i < MAX_NUM; i++) {
printf("%d ", nums[i]);
}
int target = 42;
int idx = binary_search(nums, MAX_NUM, target);
if (idx != -1) {
printf("\nFound %d at index %d", target, idx);
} else {
printf("\n%d not found", target);
}
return 0;
}
```
这段代码中,我们先生成了一个由`MAX_NUM`个随机整数构成的数组。然后使用堆排序算法对数组进行排序,并使用折半查找算法查找其中的一个数。输出结果如下:
```
13 62 96 13 97 90 48 37 77 83
Sorted:
13 13 37 48 62 77 83 90 96 97
42 not found
```
阅读全文