-
排序函数 qsort
// 头文件 <stdlib.h>
void qsort(void *base/*数组的起始地址*/, size_t nmemb/*数组元素个数*/, size_t size/* 数组每个元素的大小*/,
int (*compar)(const void *, const void *));
The qsort() function sorts an array with nmemb elements of size size.
The base argument points to the start
of the array.
The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.
/*排序结果默认升序,可以通过修改compare 函数来达到降序的结果 */
The comparison function must return an integer less than, equal to, or greater than zero if the first argument
is considered to be respectively less than, equal to, or greater than the second. If two members compare as
equal, their order in the sorted array is undefined.
/*
假设自定的compare 函数的为int (*compar)(const void *a, const void *b)
则返回值应该是,如果a < b 则小于0, 如果元素a > b 则小于0,如果相等则 返回 0;
如果a == b,这两个元素的再排序完成的数组中位置不确定, 属于不稳定的排序算法
*/
百度百科也有资料介绍, 比较通俗易懂
// 代码来自wikipedia
#include <stdlib.h>
/* Comparison function. Receives two generic (void) pointers to the items under comparison. */
int compare_ints(const void *p, const void *q) {
int x = *(const int *)p;
int y = *(const int *)q;
/* Avoid return x - y, which can cause undefined behaviour
because of signed integer overflow. */
if (x < y)
return -1; // Return -1 if you want ascending, 1 if you want descending order.
else if (x > y)
return 1; // Return 1 if you want ascending, -1 if you want descending order.
return 0;
}
/* Sort an array of n integers, pointed to by a. */
void sort_ints(int *a, size_t n) {
qsort(a, n, sizeof(*a), compare_ints);
}