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