升序排序
/*快速排序算法排序规则
*/
int32_t CmpCb(const void* _a, const void* _b)
{uint16_t* a = (uint16_t*)_a;uint16_t* b = (uint16_t*)_b;int32_t val = 0;if (*a > *b){val = 1;}else if (*a < *b){val = -1;}else {val = 0;}return val;
}int main()
{// 创建局部数组uint16_t num[10] = { 5,7,8,1,26,52,9,3,14,56 };uint16_t sz = sizeof(num) / sizeof(num[0]);// C语言库函数提供的排序函数qsort(num, sz, sizeof(num[0]), CmpCb);// for循环打印输出排序玩成后的数据for (uint8_t i = 0; i < sz; i++) {printf("num[%d] = %d.\n",i,num[i]);}
}
结果:
降序排序
#define _CRC_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>/*快速排序算法排序规则
*/#if 0int32_t CmpCb(const void* _a, const void* _b){uint16_t* a = (uint16_t*)_a;uint16_t* b = (uint16_t*)_b;int32_t val = 0;if (*a > *b){val = 1;}else if (*a < *b){val = -1;}else {val = 0;}return val;}
#else
/*快速排序算法排序规则
*/
int32_t CmpCb(const void* _a, const void* _b)
{uint16_t* a = (uint16_t*)_a;uint16_t* b = (uint16_t*)_b;int32_t val = 0;if (*a > *b){val = -1;}else if (*a < *b){val = 1;}else{val = 0;}return val;
}#endifint main()
{// 创建局部数组uint16_t num[10] = { 5,7,8,1,26,52,9,3,14,56 };uint16_t sz = sizeof(num) / sizeof(num[0]);// C语言库函数提供的排序函数qsort(num, sz, sizeof(num[0]), CmpCb);// for循环打印输出排序玩成后的数据for (uint8_t i = 0; i < sz; i++) {printf("num[%d] = %d.\n",i,num[i]);}
}
结果:
结构体排序
#define _CRC_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>// 排序结构体
typedef struct
{uint16_t id;uint8_t score;
}StuInfo_t;#if 0int32_t CmpCb(const void* _a, const void* _b){uint16_t* a = (uint16_t*)_a;uint16_t* b = (uint16_t*)_b;int32_t val = 0;if (*a > *b){val = 1;}else if (*a < *b){val = -1;}else {val = 0;}return val;}
#else/*快速排序算法排序规则
*/
int32_t CmpCb(const void* _a, const void* _b)
{uint16_t* a = (uint16_t*)_a;uint16_t* b = (uint16_t*)_b;int32_t val = 0;if (*a > *b){val = -1;}else if (*a < *b){val = 1;}else{val = 0;}return val;
}int32_t StuCmpCb(const void* _a, const void* _b)
{StuInfo_t* a = (StuInfo_t*)_a;StuInfo_t* b = (StuInfo_t*)_b;int32_t val = 0;if (a->score > b->score){val = -1;}else if (a->score < b->score){val = 1;}else{val = 0;}return val;
}#endifint main()
{// 创建局部数组uint16_t num[10] = { 5,7,8,1,26,52,9,3,14,56 };uint16_t sz = sizeof(num) / sizeof(num[0]);// C语言库函数提供的排序函数qsort(num, sz, sizeof(num[0]), CmpCb);// for循环打印输出排序玩成后的数据for (uint8_t i = 0; i < sz; i++) {printf("num[%d] = %d.\n",i,num[i]);}// 定义一个结构体数组StuInfo_t stuInfo[5] ={{1,90},{2,95},{3,69},{4,70},{5,80}};// C语言库函数提供的排序函数qsort(stuInfo, 5, sizeof(stuInfo[0]), StuCmpCb);// for循环打印输出排序玩成后的数据for (uint8_t i = 0; i < 5; i++){printf("student_id = %d, score = %d.\n", stuInfo[i].id, stuInfo[i].score);}}
结果: