C 库函数 void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) 对数组进行排序。
- base -- 指向要排序的数组的第一个元素的指针。
- nitems -- 由 base 指向的数组中元素的个数。
- size -- 数组中每个元素的大小,以字节为单位。
- compar -- 用来比较两个元素的函数。
代码Demo
/*server.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int cmp(const void* a, const void* b)
{
int* peopleA = *(int**)a;
int* peopleB = *(int**)b;
int wA = peopleA[0];
int wB = peopleB[0];
int kA = peopleA[1];
int kB = peopleA[1];
if (wA == wB) {
return kA - kB;
}
return wB - wA;
}
int** ReconstructQueue(int** people, int peopleSize)
{
qsort(people, peopleSize, sizeof(int*), cmp);
int** ret = (int**)malloc(sizeof(int*) * peopleSize);
int length = 0;
for (int i = 0; i < peopleSize; i++) {
ret[i] = (int*)malloc(sizeof(int) * 2);
ret[i][0] = people[i][0];
ret[i][1] = people[i][1];
// ret[i] = people[i]
}
return ret;
}
int main()
{
int a[6][2] = {{8, 0}, {4, 4}, {8, 1}, {5, 0}, {6, 1}, {5, 2}};
int* tmp[6] = {0};
int** people = NULL;
for (int i = 0; i < 6; i++) {
tmp[i] = a[i];
}
people = tmp;
people = ReconstructQueue(people, 6);
for (int i = 0; i < 6; i++) {
printf("the res is [%d, %d]\n", people[i][0], people[i][1]);
}
}
本文详细介绍了C标准库中的qsort()函数,包括其参数含义及使用方法,并通过一个具体的排序示例展示了如何自定义比较函数来实现复杂数据结构的有效排序。

1203

被折叠的 条评论
为什么被折叠?



