http://zh.wikipedia.org/wiki/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F
#include <stdio.h>
#include <stdlib.h>
/* 数据交换 */
void swap(int *a, int *b)
{
int tmp;
tmp = *a; *a = *b; *b = tmp;
}
void quick_sort(int a[], int left, int right)
{
int i = left + 1, j = right;
int key = a[left];
if (left >= right) return;
/* 从i++和j--两个方向搜索不满足条件的值并交换 *
* 条件为:i++方向小于key,j--方向大于key */
while (1) {
while (a[j] > key) j--;
while (a[i] < key&&i<j) i++;
if(i >= j) break;
swap(&a[i],&a[j]);
if(a[i]==key)j--;
else i++;
}
/* 关键数据放到‘中间’ */
swap(&a[left],&a[j]);
if(left < i - 1) quick_sort(a, left, i - 1);
if(j + 1 < right) quick_sort(a, j + 1 , right);
}
void main()
{
int i;
int num_array[20];
srand(0);
printf("\r\n init: ");
for(i = 0; i < 20; i++) {
num_array[i] = rand()%1000;
printf("%d ", num_array[i]);
}
quick_sort(num_array, 0, 19);
printf("\r\n quick sort: ");
for(i = 0; i < 20; i++) {
printf("%d ", num_array[i]);
}
}
C89标准在stdlib.h中定义了抽象数据类型的快速排序函数 qsort://尽量用这个接口。
#include <stdio.h>
#include <stdlib.h>
static int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
void main()
{
int i;
int num_array[20];
srand(0);
printf("\r\n init: ");
for(i = 0; i < 20; i++) {
num_array[i] = rand()%1000;
printf("%d ", num_array[i]);
}
qsort(num_array, 20, sizeof(int), cmp);
printf("\r\n quick sort: ");
for(i = 0; i < 20; i++) {
printf("%d ", num_array[i]);
}
}
本文介绍了两种快速排序的方法:一种是手动实现的快速排序算法,另一种则是使用C标准库中的qsort函数进行排序。通过实例演示了如何对整数数组进行排序。
9万+

被折叠的 条评论
为什么被折叠?



