快速排序是對冒泡排序的一種改進。快速排序是選定一個樞軸,通過一趟排序使得樞軸左側的元素都比樞軸元素小,右邊元素都比樞軸元素大,然後再遞歸的對兩側元素同樣處理,最後達到整個序列的有序。
繼續度娘盜圖。。。
#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;
}