首页 > 编程语言 > 详细

快速排序

时间:2015-06-22 16:27:04      阅读:145      评论:0      收藏:0      [点我收藏+]

快速排序是对冒泡排序的一种改进。快速排序是选定一个枢轴,通过一趟排序使得枢轴左侧的元素都比枢轴元素小,右边元素都比枢轴元素大,然后再递归的对两侧元素同样处理,最后达到整个序列的有序。

继续度娘盗图。。。

技术分享

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
#define maxn 20
typedef struct SqList
{
    int r[maxn];
    int Length;
}SqList;

void InitSqList(SqList &L,int n)
{
    int num;
    for(int i=0; i<maxn; i++)
       L.r[i] = 0;
    for(int i=1; i<=n; i++)
    {
        cin>>num;
        L.r[i] = num;
    }
    L.Length = n;
}

void PrintSqList(SqList L)
{
    for(int i=1; i<=L.Length; i++)
        cout<<L.r[i]<<" ";
}

//返回枢轴位置
int Partition(SqList &L,int low,int high)
{
    int  temp;
    temp = L.r[low];
    L.r[0] = L.r[low];
    while(low<high)
    {
        while(low<high&&L.r[high]>=temp) high--;
          L.r[low] = L.r[high];
        while(low<high&&L.r[low]<=temp) low++;
          L.r[high] = L.r[low];
    }
    L.r[low] = L.r[0];
    return low;
}

void QSort(SqList &L,int low,int high)
{
    int add;
    if(low<high)
    {
        add = Partition(L,low,high);
        QSort(L,low,add-1);
        QSort(L,add+1,high);
    }
}

void QuickSort(SqList &L)
{
    QSort(L,1,L.Length);
}

int main()
{
    SqList L;
    int n;
    cin>>n;
    InitSqList(L,n);
    QuickSort(L);
    PrintSqList(L);
    return 0;
}


 

快速排序

原文:http://blog.csdn.net/tingyu1995/article/details/46593477

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!