快速排序就平均时间而言,是目前认为最好的一种内部排序算法。
快速排序的基本思想是,通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分的记录的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。
简单实现代码
#include <stdio.h>
int parttion(int *a,int low,int high)
{
int pos=a[low];
while(low<high)
{
while(low<high&&a[high]>=pos)
{
high--;
}
a[low]=a[high];
while(low<high&&a[low]<=pos)
{
low++;
}
a[high]=a[low];
}
a[low]=pos;
return low;
}
void quickSort(int *a,int low,int high)
{
int pos;
if(low<high)
{
pos=parttion(a,low,high);
quickSort(a,low,pos-1);
quickSort(a,pos+1,high);
}
}
int main()
{
int a[10]={1,2,3,4,2,3,1,2,5,4};
quickSort(a,0,9);
for(int i=0;i<10;++i)
{
printf("%d\t",a[i]);
}
printf("\n");
return 0;
}
代码注意事项:
1、在进行parttion的时候,一定要注意,先进行从high到low的扫描。因为我们是吧low所在元素作为枢纽关键字,所以low所在的元素已经被保存,所以
while(low<high&&a[high]>=pos){ high--; } a[low]=a[high];
执行这段代码的时候,不会出现元素丢失。