交換排序------冒泡法 及其最佳化

來源:互聯網
上載者:User

標籤:經典   swa   []   ios   下標   log   複雜   標誌位   時間複雜度   

上大學學資料結構的時候就學過  冒泡法,   作為比較經典的排序方式由於其時間複雜較高一直作為入門級的演算法,雖然冒泡演算法在實際應用中較少但是也是有一定的研究價值的,這裡給出三種實現,第一種為原始演算法時間複雜度為 O(n);  第二種為加入標誌位, 使演算法在待排序資料已成有序情況前提前結束;  第三種,記錄每一趟排序後最後交換的兩個元素中的較小下標並將其作為下次排序的上限, 使演算法可以在待排序資料中直接跨過尾部已經有序的資料元素減少比較次數。

 

冒泡排序原始演算法:

#include <iostream>using namespace std;template <class T>void bubbleSort_0(T A[], int n){    for(int i=1; i<n; i++)    {        for(int j=0;j<n-i;j++)        {            if(A[j]>A[j+1])            {                swap(A[j], A[j+1]);            }        }    }}

 

加入標誌位後:

template <class T>void bubbleSort_1(T A[], int n){    int flag=1;    for(int i=1; i<n && flag; i++)    {        flag=0;        for(int j=0;j<n-i;j++)        {            if(A[j]>A[j+1])            {                swap(A[j], A[j+1]);                flag=1;            }        }    }}

 

 

記錄每一趟最後交換的一對元素中較小的下標

template <class T>void bubbleSort_2(T A[], int n){    int i, j;    int lastExchangeIndex;    i=n-1;    while(i>0)    {        lastExchangeIndex=0;        for(j=0;j<i;j++)        {            if(A[j]>A[j+1])            {                swap(A[j], A[j+1]);                lastExchangeIndex=j;            }        }        i=lastExchangeIndex;    }}

 

 

主函數:

int main(){    int A[]={8, 6, 9, 7, 5, 0, 4, 1, 3, 2};    int n=10;    bubbleSort_2(A, n);    for(int i=0;i<n;i++)        cout<<A[i]<<" ";    cout<<endl;    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.