快速排序

来源:互联网 发布:c语言输出钻石图案 编辑:程序博客网 时间:2024/05/17 08:17

1、算法原理

快速排序(quicksort)是在实践中最快的已知排序算法,它的平均运行时间是O(NlogN)。该算法之所以特别快,主要是由于非常精炼和高度优化的内部循环。像归并排序一样,快速排序也是一种分治的递归算法。将数组S排序的基本算法由下列简单的四步组成:

(1)如果S中元素个数是0或1,则返回。

(2)取S中一个元素v,称之为枢纽元(pivot)。

(3)将S-{v}(S中其余元素)分成两个不相交的集合:S1={x∈S-{v}|x≤v}和S2={x∈S-{v}|x≥v}。

(4)返回{quicksort(S1)}后,继随v,继而{quicksort(S2)}。


2、代码

/*++++++++++++++++++++++++++++++++++++++快速排序(C版)++author:zhouyongxyz2013-4-15 9:39+++++++++++++++++++++++++++++++++++++*/#include <cstdio>#define N 8typedef int ElementType;void Swap(ElementType &a,ElementType &b);ElementType Median3(ElementType a[],int left,int right);void QSort(ElementType a[],int left,int right);void QuickSort(ElementType a[],int n);int main(){int a[N]={4,3,5,2,9,7,6,8};QuickSort(a,N);for(int i=0;i<N;i++)printf("%d ",a[i]);printf("\n");return 0;}void QuickSort(ElementType a[],int n){QSort(a,0,n-1);}ElementType Median3(ElementType a[],int left,int right){int center=(left+right)/2;if(a[left]>a[center])Swap(a[left],a[center]);if(a[left]>a[right])Swap(a[left],a[right]);if(a[center]>a[right])Swap(a[center],a[right]);Swap(a[center],a[right-1]);return a[right-1];}void Swap(ElementType &a,ElementType &b){int tmp;tmp=a;a=b;b=tmp;}void QSort(ElementType a[],int left,int right){int i,j;ElementType pivot;if(left<right){pivot=Median3(a,left,right);i=left;j=right-1;while(1){while(a[i]<pivot) i++;while(a[j]>pivot) j--;if(i<j)Swap(a[i],a[j]);elsebreak;}QSort(a,left,i-1);QSort(a,i+1,right);}}


原创粉丝点击