排序-快速排序

快速排序

這種算法是對冒泡排序的改進喲,算是比較快的排序了ios

這裏有原理講解,嘿嘿嘿算法

//算法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);
}
相關文章
相關標籤/搜索