您的位置:首页 > 其它

快速排序

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

继续度娘盗图。。。



#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: