qsort包含在<stdlib.h>头文件中,此函数根据你给的比较条件进行快速排序,通过指针移动实现排序。排序之后的结果仍然放在原数组中。使用qsort函数必须自己写一个比较函数。 函数原型: void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) ); 用法以及参数说明: Sorts the num elements of the array pointed by base, each element size bytes long, using the comparator function to determine the order. The sorting algorithm used by this function compares pairs of values by calling the specified comparator function with two pointers to elements of the array. The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order. base 一、对int类型数组排序 int cmp ( const void *a , const void *b ) qsort(num,100,sizeof(num[0]),cmp); 二、对char类型数组排序(同int类型) char word[100]; int cmp( const void *a , const void *b ) qsort(word,100,sizeof(word[0]),cmp); 三、对double类型数组排序 int cmp( const void *a , const void *b ) qsort(in,100,sizeof(in[0]),cmp); 四、对结构体一级排序 struct Sample //按照data的值从小到大将结构体排序 int cmp( const void *a ,const void *b) struct Sample *c = (struct Sample *)a; struct Sample *d = (struct Sample *)b; qsort(s,100,sizeof(s[0]),cmp); 五、对结构体二级排序 struct Sample int cmp( const void *a , const void *b ) qsort(s,100,sizeof(s[0]),cmp); 六、对字符串进行排序 struct Sample int cmp ( const void *a , const void *b ) qsort(s,100,sizeof(s[0]),cmp); 附加一个完整点的代码,对字符串二维数组排序: #include <stdio.h> char s[2001][1001]; int cmp(const void *a, const void *b){ int main(){ |
快排函数
最新推荐文章于 2023-07-17 22:38:53 发布