快速排序是一种最常见的高效排序算法,时间复杂度为O(n2),但是平均的时间复杂度是O(n·lgn)。而且可以证明,随机选取参照值的快速排序的时间复杂度期望值为O(n·lgn)。
C语言中已经存在快速排序的函数qsort:
#include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
#include <stdio.h> #include <string.h> #include <stdlib.h> void *quicksort(void *base, size_t nmeb, size_t size, int(*compar)(const void *, const void *)) { if (nmeb < 2) return; int i, j, key; key = rand() % nmeb; swap(base, base + key * size, size); i = 1; j = nmeb - 1; while (i < j) { if (compar(base + i * size, base) > 0) { swap(base + i * size, base + j * size, size); --j; } else ++i; } if (compar(base, base + i * size) > 0) swap(base, base + i * size, size); quicksort(base, i, size, compar); quicksort(base + i * size, nmeb - i, size, compar); } void swap(void *p1, void *p2, size_t size) { void *temp; temp = malloc(size); if (temp == NULL) { exit(EXIT_FAILURE); } memcpy(temp, p1, size); memcpy(p1, p2, size); memcpy(p2, temp, size); free(temp); } static int comparStr(const void *p1, const void *p2) { return strcmp(* (char * const *) p1, * (char * const *) p2); } static int comparInt(const void *p1, const void *p2) { return (*(const int *) p1 - *(const int *) p2); }
简单的测试代码如下:
int main(int argc, char *argv[]) { int i; int arr[5] = {4, 2, 1, 3, 5}; srand(time(NULL)); printf("Integer Sort\n"); printf("Original: "); for (i = 0; i < 5; i++) printf("%d ", arr[i]); printf("\n"); quicksort(arr, 5, sizeof(int), comparInt); printf("Sorted : "); for (i = 0; i < 5; i++) printf("%d ", arr[i]); printf("\n\n"); if (argc < 2) exit(EXIT_SUCCESS); printf("String Sort\n"); printf("Original: "); for (i = 1; i < argc; i++) printf("%s ", argv[i]); printf("\n"); quicksort(&argv[1], argc - 1, sizeof(argv[1]), comparStr); printf("Sorted : "); for (i = 1; i < argc; i++) printf("%s ", argv[i]); printf("\n"); exit(EXIT_SUCCESS); }
运行结果如下:
roo@ubuntu:~$ ./a.out linux windows mac Integer Sort Original: 4 2 1 3 5 Sorted : 1 2 3 4 5 String Sort Original: linux windows mac Sorted : linux mac windows