内部排序之 快速排序

来源:互联网 发布:淘宝打不开怎么办 编辑:程序博客网 时间:2024/04/23 18:15

快速排序

本文整理我对快速排序的学习与理解。

时间复杂度好的情况下O(n*logn)最坏的情况下O(n*n)

对于一组序列 a[] = {6, 9,10, 8, 1, 19,  4};

1、选择第一个元素作为分界值temp,比temp大的数往右移,比temp小的数往左移,分为两类

2、把temp移到中间,其左右两个区间看做新的待排序的序列,重复第1步。

这是一个递归过程,直到区间长度为1,return;

【代码1(递归法)】:

#include<bits/stdc++.h>using namespace std;void Qsort(int *a,int low,int high)//[low,high]闭区间{    if(low>=high)return;    int l=low,r=high;    int temp=a[l];//记下首元素,作为分界值    while(l<r)    {        while(l<r&&a[r]>=temp)r--;//右端点左移,直到值<temp,需要放到左边去        a[l]=a[r];        while(l<r&&a[l]<=temp)l++;        a[r]=a[l];    }    a[l]=temp;    Qsort(a,low,l-1);    Qsort(a,l+1,high);}int main(){    int a[10]={49,38,65,27,79,98,12,42,100,9};    Qsort(a,0,9);    for(int i=0;i<10;i++)        printf("%d ",a[i]);}

【代码2非递归】

#include<bits/stdc++.h>using namespace std;void Qsort(int *a,int n){    int l,r,low,high;    queue<int>q;    q.push(0);q.push(n-1);    while(!q.empty())    {        low=l=q.front();q.pop();        high=r=q.front();q.pop();        int temp=a[l];//记下首元素,作为分界值        while(l<r)        {            while(l<r&&a[r]>=temp)r--;//右端点左移,直到值<temp,需要放到左边去            a[l]=a[r];            while(l<r&&a[l]<=temp)l++;            a[r]=a[l];        }        a[l]=temp;        if(low<l-1){q.push(low);q.push(l-1);}        if(l+1<high){q.push(l+1);q.push(high);}    }}int main(){    int a[]={4,8,2,8,10,5};    Qsort(a,6);    for(int i=0;i<6;i++)        printf("%d ",a[i]);}

原创粉丝点击