如何用C语言qsort实现多条件排序,模拟指定SQL排序逻辑?
C语言qsort实现多条件排序问题
需求
需要用C语言的qsort复现以下SQL的排序逻辑:
select * from (values('Russia'),('America'),('New Zealand'),('India')) cte(a) order by a='India' desc, a asc;
期望排序结果:
+-------------+ | a | +-------------+ | India | | America | | New Zealand | | Russia | +-------------+
当前代码问题
现有自定义compare_rows函数未能正确实现该逻辑,代码如下:
char *str[ROWS][COLS] = {{"Russia", "Boxing", "Mens", "Gold"}, {"America", "Cycling", "Mens", "Gold"}, {"New Zealand", "Swimming", "Womens", "Silver"}, {"India", "Badminton", "Mens", "Bronze"}}; qsort(str,ROWS,sizeof(*str),(compare_rows)); static int compare_rows(const void * a, const void * b) { const int sort_colmn = 0; char * x1 = ((char ** ) a)[sort_colmn]; char * x2 = ((char ** ) b)[sort_colmn]; if (x2 == "India") return 1; if (x1 > x2 && x2 != "India") return 1; else if (x1 == x2) return 0; else return -1; }
错误分析与修正方案
原函数的核心问题
- 字符串比较方式错误:C语言中用
==或>比较字符串指针,实际比较的是内存地址而非字符串内容,必须使用strcmp函数来比较字符串值。 - 排序逻辑不符合需求:原逻辑没有正确实现"India"优先,再按字典序升序的多条件排序规则。
正确的比较函数实现
#include <string.h> // 必须引入strcmp的头文件 static int compare_rows(const void *a, const void *b) { const int sort_column = 0; const char *x1 = ((const char **)a)[sort_column]; const char *x2 = ((const char **)b)[sort_column]; // 判断当前字符串是否为"India" int x1_is_india = (strcmp(x1, "India") == 0); int x2_is_india = (strcmp(x2, "India") == 0); // 优先处理"India"的排序 if (x1_is_india && !x2_is_india) { return -1; // x1是India,排在x2前面 } else if (!x1_is_india && x2_is_india) { return 1; // x2是India,排在x1前面 } // 非India的元素按字典序升序排列 return strcmp(x1, x2); }
逻辑说明
- 先通过
strcmp判断两个元素是否为"India",确定优先级。 - 若其中一个是"India",直接调整排序顺序让其排在前面。
- 若两者都不是或都是"India",则调用
strcmp按字典序升序排序,strcmp的返回值完全符合qsort比较函数的要求:- 返回负数:x1排在x2之前
- 返回0:两者排序位置相同
- 返回正数:x2排在x1之前
内容的提问来源于stack exchange,提问作者jian
相关产品推荐
相关产品推荐

