C语言对二维数组快速排序
时间: 2023-05-17 09:02:49 浏览: 80
可以使用qsort函数来对二维数组进行快速排序,具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return (*(int **)a)[0] - (*(int **)b)[0];
}
void sort(int **arr, int n) {
qsort(arr, n, sizeof(int *), cmp);
}
int main() {
int arr[3][2] = {{3, 1}, {2, 5}, {1, 4}};
int *p[3] = {arr[0], arr[1], arr[2]};
sort(p, 3);
for (int i = 0; i < 3; i++) {
printf("%d %d\n", p[i][0], p[i][1]);
}
return 0;
}
```
这段代码可以对一个3行2列的二维数组进行排序,输出结果为:
```
1 4
2 5
3 1
```
其中,cmp函数是用来比较两个二维数组元素大小的函数,sort函数是用来对二维数组进行排序的函数,main函数中的arr是一个3行2列的二维数组,p是一个指向arr中每一行的指针数组,通过调用sort函数对p进行排序,最后输出排序后的结果。
相关问题
C语言对二维字符数组快速排序
可以使用qsort函数对二维字符数组进行快速排序,具体实现可以参考以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
int cmp(const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}
int main() {
char str[MAX_LEN][MAX_LEN];
int n;
printf("请输入字符串个数:");
scanf("%d", &n);
printf("请输入字符串:\n");
for (int i = 0; i < n; i++) {
scanf("%s", str[i]);
}
qsort(str, n, sizeof(str[0]), cmp);
printf("排序后的字符串为:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", str[i]);
}
return 0;
}
对于二维字符数组的快速排序,我们需要自定义一个比较函数cmp,该函数的作用是比较两个字符串的大小关系。在主函数中,我们先输入字符串的个数和具体内容,然后调用qsort函数进行排序,最后输出排序后的结果。
c语言二维数组找中位数
以下是一个例子:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define COLS 3
int compare(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
int main()
{
int arr[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int size = ROWS * COLS;
int *tmp = malloc(sizeof(int) * size);
int cnt = 0;
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
tmp[cnt++] = arr[i][j];
}
}
qsort(tmp, size, sizeof(int), compare);
int median = tmp[size / 2];
printf("The median is %d\n", median);
free(tmp);
return 0;
}
```
输出:
```
The median is 5
```
该程序将二维数组转换为一个一维数组,然后使用快速排序算法将其排序。最后,中位数是排序后数组的中间元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_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)