快速排序是基于分治策略的一种排序算法。其基本思想是,对于输入的数组a[p:r],按以下三个步骤进行排序:
- 分解:将a[p:r]分解成a[p:q-1],a[q],和a[q+1:r]。在a[p:q-1]中任何一个元素都小于a[q],在a[q+1:r]中,任何一个元素都大于a[q]。
- 递归求解:通过递归调用快速排序算法,对两边的子数组进行排序
- 合并:由于已经排好序,该步不作运算。
1 算法
#include<stdio.h>
int Partition(int a[],int p,int r);
void QuickSort(int a[],int p,int r);
int main(){
int a[5] = {6,5,74,78,4};
QuickSort(a,0,4);
for(int i = 0;i<5;i++){
printf("%d ",a[i]);
}
}
void QuickSort(int a[],int p,int r){
if(p<r){
int q = Partition(a,p,r); //方法作用数组后,数组左边小于q,右边大于q,返回一个q
QuickSort(a,p,q-1); //左边子数组排序
QuickSort(a,q+1,r); //右边子数组排序
}
}
int Partition(int a[],int p,int r){
int i = p,j = r+1;
int x = a[p]; //选取第一个元素为基准元素
while(true){
while(a[++i]<x && i<r); //在左边序列找到小于x元素的下标
while(a[--j]>x); //在右边找到大于x元素的下标
if(i>=j) //当左边序列或右边序列找不到相应的下标时,打破循环 ,即排序结束
break;
int t = a[i];
a[i] = a[j];
a[j] = t;
}
a[p] = a[j]; //将首元素与中间最小的元素替换,即左边小于右边大于
a[j] = x;
return j;
}
2 算法分析
2.1 复杂度分析:
最坏情况下,即数组接近有序时时间复杂度为O(n^2)
平均情况下为O(nlogn)
稳定性分析:
不稳定