用c语言实现编写程序,所完成的功能为:(1)建立数组,元素为12, 21, 5, 25, 31, 11, 30, 26, 53, 87, 20, 3, 65, 48, 67, 91。(2)使用快速排序法对数组进行排序。(3)使用二分查找法,搜索元素3的位置。
时间: 2023-10-06 11:13:15 浏览: 40
以下是用C语言实现所需功能的程序:
```c
#include <stdio.h>
// 快速排序函数
void quickSort(int arr[], int left, int right) {
int i = left, j = right, temp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
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(arr[0]);
// 打印原始数组
printf("原始数组:\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
// 快速排序
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;
}
```
输出结果如下:
```
原始数组:
12 21 5 25 31 11 30 26 53 87 20 3 65 48 67 91
排序后的数组:
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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)