冒泡排序演算法

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   for   div   sp   

冒泡排序演算法的時間複雜度是什嗎?

時間複雜度是O(n^2)。

 

 1 #include "stdafx.h" 2 #include <iostream> 3 using namespace std; 4 void Swap(int &a, int &b) 5 { 6     int temp = a; 7     a = b; 8     b = temp; 9 }10 11 void Bubble1(int *array, int length)12 {13     for (int i=length-1;i>0;--i) //首先是要比較多少趟,每一趟冒泡可以確定一個值。最後一趟只剩一個就不用比較了(所以是i>0而不是i>=0)。14     {15         for (int j=0;j<i;++j)16         {17             if (array[j]>array[j+1])  //升序(降序 < )18             {19                 Swap(array[j], array[j+1]);20             }21         }22     }23 }24 25 void Bubble2(int *array, int length)26 {27     for (int i=0;i < length - 1;++i) //首先是要比較多少趟,每一趟冒泡可以確定一個值。最後一趟只剩一個就不用比較了(所以是i < length - 1)。28     {29         for (int j=1;j < length - i;++j)30         {31             if (array[j-1]>array[j])  //升序(降序 < )32             {33                 Swap(array[j-1], array[j]);34             }35         }36     }37 }38 39 //設定標誌位最佳化的及時終止版40 void Bubble3(int *array, int length)41 {42     bool swapHappend;43     for (int i=0;i < length - 1;++i) //首先是要比較多少趟,每一趟冒泡可以確定一個值。最後一趟只剩一個就不用比較了(所以是i < length - 1)。44     {45         swapHappend = false;46         for (int j=1;j < length - i;++j)47         {48             if (array[j-1]>array[j])  //升序(降序 < )49             {50                 Swap(array[j-1], array[j]);51                 swapHappend = true;52             }53         }54         if (!swapHappend)55             break;        56     }57 }58 59 int _tmain(int argc, _TCHAR* argv[])60 {61     int array[] = {2,9,6,3,8,5,1,4,7};62 63     /*Bubble1(array, 9);*/64     Bubble2(array, 9);65     /*Bubble3(array, 9);*/   66 67     for (int i=0;i<9;++i)68         cout<<array[i]<<endl;69 70     getchar();71     return 0;72 }

 

冒泡排序演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.