快速排序的基本思想:通过一次排序将待排记录分割成独立的两部分,其中一部分记录关键字均比另一部分记录的关键字小,则可以分别对这两部分记录继续进行排序,以达到整个序列有序的目的
#include<stdio.h>
void swap(int k[],int low,int high)
{
int tmp;
tmp = k[low];
k[low] = k[high];
k[high] = tmp;
}
int Partition(int k[],int low,int high)
{
int point;
point = k[low];
while(low<high)
{
while(low < high && k[high]>=point)
{
high--;
}
swap(k,low,high);
while(low<high && k[low] <= point)
{
low++;
}
swap(k,low,high);
}
}
void QSort(int k[],int low,int high)
{
int point;
if(low < high)
{
point = Partition(k,low,high);
QSort(k,low,point-1);
QSort(k,point + 1,high);
}
}
void QuickSort(int k[],int n)
{
QSort(k,0,n-1);
}
int main()
{
int i,a[10]={5,2,6,0,3,9,1,7,4,8};
QuickSort(a,10);
for(i = 0;i<10;i++)
printf("%d",a[i]);
printf("\n\n");
return 0;
}
另外一种方法
参考链接
#include <stdio.h>
void quick_sort( int *a, int n)
{
int i, j, p, tmp;
if (n < 2) return;
p = a[n / 2]; // Get the middle element as pivot ..
for ( i = 0, j = n -1;; i++, j--) {
while (a[i] < p)
i++;
while (p < a[j])
j--;
if ( i >= j)
break;
tmp = a[i]; a[i] = a[j]; a[j] = tmp; //swap both ..
}
quick_sort( a, i);
quick_sort( a + i, n - i);
}
int main(void)
{
int a[] = { 2, 5, 7, 3, -1, 1, 4};
int n = sizeof a /sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n -1 ? "\n" : " ");
quick_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n -1 ? "\n" : " ");
return 0;
}
p取数组中间值,还可以优化。
三数取中或者九数取中。