C语言stdlib.h中自带的qsort

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int funcmp(const void *pa, const void *pb)
{
    
    
    return strcmp(*(char**)pa, *(char**)pb) > 0 ? 1 : -1;
}
int main(int argc, char *argv[])
{
    
    
	char *str[6] = {
    
    "google", "apple", "facebook", "orcale", "dajiang", "amazon"};
    qsort(str, sizeof(str) / sizeof(str[0]), sizeof(str[0]), funcmp);
    for (int i = 0; i < 6; i++) {
    
    
        printf("%s\n", str[i]);
    }
    return 0;
}

qsort是stdlib.h中自带的快速排序函数,这个函数有4个参数,第1个参数是待排序的数组名,第2个参数是有多少个元素需要排序,第3个参数是每个元素占用的字节数,第4个参数是函数指针,需要自己实现对应的排序方式,是从小到大还是从大到小。

猜你喜欢

转载自blog.csdn.net/cp_srd/article/details/105221111
今日推荐