快速排序

来源:互联网 发布:淘宝装修代码怎么写 编辑:程序博客网 时间:2024/06/15 18:52
快速排序是基于分治思想的排序,以递增排序为例:
首先选取一个基准元素pivot,将小于pivot的元素移到其左侧,
大于pivot的元素移到其右侧。这一轮固定了pivot的位置。
然后对其左右两侧执行相同的操作。
快速排序平均时间复杂度O(nlogn),最差时间复杂度O(n^2);空间复杂度O(1)。

示例代码如下:

#include<stdio.h>#define Elemtype intint  partion(Elemtype A[],int low,int high){Elemtype pivot=A[low];while(low<high){while(low<high&&A[high]>=pivot)high--;A[low]=A[high];while(low<high&&A[low]<=pivot)low++;A[high]=A[low];}A[low]=pivot;return low;}void quicksort(int A[],int low,int high){if(low<high){int pivotpos=partion(A,low,high);quicksort(A,low,pivotpos-1);quicksort(A,pivotpos+1,high);}}int main(){int A[12]={12,3,4,5,6,77,4,22,22,3,5,7};quicksort(A,0,11);for(int i=0;i<12;i++){printf("%d ",A[i]);}}


0 0