用C语言编写程序,所完成的功能为:(1)建立数组,元素为12, 21, 5, 25, 31, 11, 30, 26, 53, 87, 20, 3, 65, 48, 67, 91。(2)使用快速排序法对数组进行排序。(3)使用二分查找法,搜索元素3的位置。
时间: 2023-10-05 21:11:41 浏览: 41
以下是使用C语言实现的程序:
```c
#include <stdio.h>
// 快速排序算法
void quick_sort(int arr[], int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right;
int pivot = arr[left];
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
}
arr[i] = arr[j];
while (i < j && arr[i] <= pivot) {
i++;
}
arr[j] = arr[i];
}
arr[i] = pivot;
quick_sort(arr, left, i - 1);
quick_sort(arr, i + 1, right);
}
// 二分查找算法
int binary_search(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {12, 21, 5, 25, 31, 11, 30, 26, 53, 87, 20, 3, 65, 48, 67, 91};
int size = sizeof(arr) / sizeof(int);
// 使用快速排序算法对数组进行排序
quick_sort(arr, 0, size - 1);
// 输出排序后的数组
printf("排序后的数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 使用二分查找算法搜索元素3的位置
int target = 3;
int pos = binary_search(arr, size, target);
// 输出搜索结果
if (pos == -1) {
printf("找不到元素 %d\n", target);
} else {
printf("元素 %d 的位置为 %d\n", target, pos);
}
return 0;
}
```
程序运行结果如下:
```
排序后的数组:3 5 11 12 20 21 25 26 30 31 48 53 65 67 87 91
元素 3 的位置为 0
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)