快速排序
這種演算法是對冒泡排序的改進喲,算是比較快的排序了
這里有原理講解,嘿嘿嘿
//演算法8.5 快速排序
#include <iostream>
using namespace std;
#define MAXSIZE 20 //順序表的最大長度
typedef struct
{
int key;
char *otherinfo;
}ElemType;
//順序表的存盤結構
typedef struct
{
ElemType *r; //存盤空間的基地址
int length; //順序表長度
}SqList; //順序表型別
int Partition(SqList &L,int low,int high)
{
//對順序表L中的子表r[low..high]進行一趟排序,回傳樞軸位置
int pivotkey;
L.r[0]=L.r[low]; //用子表的第一個記錄做樞軸記錄
pivotkey=L.r[low].key; //樞軸記錄關鍵字保存在pivotkey中
while(low<high)
{ //從表的兩端交替地向中間掃描
while(low<high&&L.r[high].key>=pivotkey) --high;
L.r[low]=L.r[high]; //將比樞軸記錄小的記錄移到低端
while(low<high&&L.r[low].key<=pivotkey) ++low;
L.r[high]=L.r[low]; //將比樞軸記錄大的記錄移到高端
}//while
L.r[low]=L.r[0]; //樞軸記錄到位
return low; //回傳樞軸位置
}//Partition
void QSort(SqList &L,int low,int high)
{ //呼叫前置初值:low=1; high=L.length;
//對順序表L中的子序列L.r[low..high]做快速排序
int pivotloc;
if(low<high)
{ //長度大于1
pivotloc=Partition(L,low,high); //將L.r[low..high]一分為二,pivotloc是樞軸位置
QSort(L,low,pivotloc-1); //對左子表遞回排序
QSort(L,pivotloc+1,high); //對右子表遞回排序
}
} //QSort
void QuickSort(SqList &L)
{
//對順序表L做快速排序
QSort(L,1,L.length);
} //QuickSort
void Create_Sq(SqList &L)
{
int i,n;
cout<<"請輸入資料個數,不超過"<<MAXSIZE<<"個,"<<endl;
cin>>n; //輸入個數
cout<<"請輸入待排序的資料:\n";
while(n>MAXSIZE)
{
cout<<"個數超過上限,不能超過"<<MAXSIZE<<",請重新輸入"<<endl;
cin>>n;
}
for(i=1;i<=n;i++)
{
cin>>L.r[i].key;
L.length++;
}
}
void show(SqList L)
{
int i;
for(i=1;i<=L.length;i++)
cout<<L.r[i].key<<endl;
}
int main()
{
SqList L;
L.r=new ElemType[MAXSIZE+1];
L.length=0;
Create_Sq(L);
QuickSort(L);
cout<<"排序后的結果為:"<<endl;
show(L);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/115750.html
標籤:其他
上一篇:排序-希爾排序
下一篇:排序-堆排序
