Last active
April 10, 2016 02:49
-
-
Save otaks/467da49d017537e93ad0fc5cf59799ff to your computer and use it in GitHub Desktop.
クイックソート 複数キー(複数条件)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
struct st { | |
char* AAA; | |
int BBB; | |
char* CCC; | |
}; | |
//表示 | |
void print(struct st* p, int n) { | |
for (int i = 0; i < n; i++) { | |
printf("%s\t%d\t%s\n", p[i].AAA, p[i].BBB, p[i].CCC); | |
} | |
printf("\n\n"); | |
} | |
//AAA列の比較関数 | |
int cmp_AAA(struct st* pitem1, struct st* pitem2) { | |
return strcmp(pitem1->AAA, pitem2->AAA); //昇順 | |
} | |
//BBB列の比較関数 | |
int cmp_BBB(struct st* pitem1, struct st* pitem2) { | |
return pitem2->BBB - pitem1->BBB; //降順 | |
} | |
//比較関数 | |
int cmp(const void *item1, const void *item2) | |
{ | |
//比較関数リスト | |
//※比較対象列分の比較関数を作成し、設定する。 | |
int(*func[])(struct st* pa, struct st* pb) = { &cmp_AAA , &cmp_BBB }; //比較関数リスト | |
struct st *pitem1 = (struct st*)item1; | |
struct st *pitem2 = (struct st*)item2; | |
for (int i = 0; i < sizeof(func) / sizeof(func[0]); i++) { //比較対象列分繰り返す | |
int ret = func[i](pitem1, pitem2); //比較関数実行 | |
if (ret != 0) { //前後が決定したか | |
return ret; | |
} | |
} | |
//全ての比較関数を実行しても前後関係が決定しないので、 | |
//同等なデータと判断 | |
return 0; | |
} | |
//メイン関数 | |
int main() { | |
struct st s[8] = { | |
{ "bb", 2, "xx"}, | |
{ "aa", 5, "yy" }, | |
{ "aa", 60, "ww" }, | |
{ "aa", 5, "xx" }, | |
{ "bb", 3, "yy" }, | |
{ "cc", 30, "ww" }, | |
{ "cc", 12, "xx" }, | |
{ "cc", 12, "yy" } }; | |
print(s, sizeof(s) / sizeof(s[0])); //表示 | |
qsort(s, sizeof(s) / sizeof(s[0]), sizeof(s[0]), cmp); //ソート | |
print(s, sizeof(s) / sizeof(s)[0]); //表示 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment