快速排序演算法,排序演算法

來源:互聯網
上載者:User

快速排序演算法,排序演算法

之前一篇文章寫了寫堆排序演算法的實現過程,今天進行快速排序演算法的代碼練習
說道快速排序,他的主要思想是將一個數列進行合理的劃分,劃分的標準來自樞軸的選擇,其中使用樞軸來劃分子序列,進而產生遞推的表達,而得到子序列,通過交換資料而得到整體順序一致的序列。
因此,樞軸的選取成為提高快速排序演算法效率的根本要求。
廢話不說了,基本的快排的思想在資料結構這本書中已經接觸過了,具體的實現如下:

#include <iostream>using namespace std;template<class Any>void SwapData(Any &a,Any &b){    Any tmp=a;    a=b;    b=tmp;}template<class AnyType>void OutPut(AnyType array,int len){    cout << array[0];    for(int i=1;i<len;i++)        cout << " " << array[i];    cout << endl;}/*快速排序的核心思路就是如何選擇樞軸的位置,也就是如何對整個數列進行合理的劃分。改進快速排序的演算法,其實本質就是改進對序列的劃分的方法。*/template<class AnyType>void QuickSort(AnyType array[],int left,int right,int len){    if(left<right)    {        AnyType tmp=array[left];        int i=left;        int j=right+1;        while(true)        {            while(i+1<len && array[++i]<tmp);            while(j-1>-1 && array[--j]>tmp);            if(i>=j) break;            SwapData(array[i],array[j]);        }        array[left]=array[j];        array[j]=tmp;        QuickSort(array,left,j-1,len);        QuickSort(array,j+1,right,len);    }}template<class AnyType>int MyPartition(AnyType array[],int left,int right){    AnyType tmp=array[right];    int i=left-1;    for(int j=left;j<right;j++)    {        if(array[j]<=tmp)            SwapData(array[++i],array[j]);    }    SwapData(array[i+1],array[right]);    return i+1;}template<class AnyType>void QuickSortMoreFast(AnyType array[],int left,int right){    if(left<right)    {        int q=MyPartition(array,left,right);        QuickSortMoreFast(array,left,q-1);        QuickSortMoreFast(array,q+1,right);    }}//調用C++內建函式進行排序#include <algorithm>#include <vector>void InnerQSort(){    vector<int> data;    for(int i=0;i<50;i++)        data.push_back(rand());    sort(data.begin(),data.end());    OutPut(data,data.size());}int main(){//    int array[]={5,4,7,3,9,1,8,6,10,2};//    QuickSort(array,0,sizeof(array)/sizeof(int),sizeof(array)/sizeof(int));//    QuickSortMoreFast(array,0,sizeof(array)/sizeof(int));//    OutPut(array,sizeof(array)/sizeof(int));    InnerQSort();    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.