Last active
August 29, 2015 14:01
-
-
Save nek023/0b4e7e17e135b2b74850 to your computer and use it in GitHub Desktop.
About qsort of C lang
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> | |
// 2つの要素の大小を比較して, (ソート後の配列で)どちらを先に並べるかを返す関数 | |
int compare(const void * a, const void * b) { | |
// qsort は配列の中身が何なのか (int なのか, float なのか, それとも独自のデータ型なのか) | |
// が判らないので, とりあえず (void *) 型で渡してくる. | |
// こちらはデータの中身が int だと知っているので, ここで int に戻してあげる | |
int num1 = *(int *)a; | |
int num2 = *(int *)b; | |
if (num1 < num2) { | |
return -1; // ここが 1 だと...? | |
} else if (num1 > num2) { | |
return 1; // ここが -1 だと...? | |
} else { | |
return 0; | |
} | |
// 昇順: | |
// num1 < num2 なら -1 を返す (ソート後の配列で, num1 を先に並べたい) | |
// num1 > num2 なら 1 を返す | |
// num1 == num2 なら 0 を返す | |
// 降順: | |
// num1 < num2 なら 1 を返す (ソート後の配列で, num2 を先に並べたい) | |
// num1 > num2 なら -1 を返す | |
// num1 == num2 なら 0 を返す | |
} | |
int main(int argc, char *argv[]) { | |
int array[5] = { 3, 1, 2, 5, 4 }; // int の配列 | |
// ソートする | |
qsort((void *)array, // ソートしたい配列 | |
5, // 配列の要素数 | |
sizeof(array[0]), // 配列の1つの要素のサイズ, 今回はintなのでsizeof(int)でも同じ | |
compare); // 2つの要素の大小比較に使う関数 | |
// ソートした結果を表示 | |
for (int i = 0; i < 5; i++) { | |
printf("%d: %d\n", i, array[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment