參考資訊:
https://cplusplus.com/reference/cstdlib/qsort/
使用C語言刷題時,可以使用qsort()做排序,qsort()預設使用QuickSort演算法,時間複雜度是n*log(n)
一維陣列
int mysort(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int main(int argc, char *argv[]) { int buf[] = { 40, 10, 100, 90, 20, 25 }; qsort(buf, 6, sizeof(buf[0]), mysort); return 0; }
二維陣列
int mysort(const void *a, const void *b) { return ((*(int **)a)[0] - (*(int **)b)[0]); } int main(int argc, char **argv) { int cc = 0; int **buf = NULL; buf = malloc(sizeof(int *) * 3); for (cc = 0; cc < 3; cc++) { buf[cc] = malloc(sizeof(int) * 2); } buf[0][0] = 5; buf[0][1] = 7; buf[1][0] = 1; buf[1][1] = 3; buf[2][0] = 9; buf[2][1] = 10; qsort(buf, 3, sizeof(buf[0]), mysort); return 0; }