【转】C++学习四 冒泡排序法的一些改进
冒泡排序法需要兩次掃描,所以從時間復雜度來說,是O(n2).
如果用圖形表示,是這樣的:
但是我們可以加以改進。
首先是,如果在排序中間,整個向量已經達到了有序狀態,可以直接跳出來。
這樣它的復雜度由一個三角形變為一個梯形。
?
?同時,可能存在部分有序的狀態,所以可以再次改進:
?
?深藍色為可能占用的時間復雜度。
我自己寫了一個代碼測試了一下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include<iostream> #include<vector> #include <algorithm>//question1: 使用swap()需要包含這個頭文件, using?namespace?std; ? //函數模板,這是冒泡排序的主要過程 template?<typename?T1> T1 bubble(T1 lo, T1 hi,int?*x) { ????T1 last=lo; ????while(++lo<hi) ????????if(x[lo-1]>x[lo]) ????????{ ????????????last=lo; ????????????swap(x[lo-1],x[lo]);//question2:格式是std::swap, 所以如果單獨使用 ??????????????????????????????????????????//前面還需要定義using namespace std; ????????} ????return?last; } ? template?<typename?T1>//question3:每一個模板函數都需要申明一遍參數 void?MySort(int*x, T1 lo, T1 hi ) {?while(lo<(hi=bubble(lo, hi, x))); } ? ? int?main(void) { ????//int x=0; ????//cout<<"the result is "<<x<<endl; ????int?p[7]={1,3,5,2,1,7,2}; ????int?low=0; ????int?high=7; ????MySort(p,low,high); ????for(int?i=0;i<7;i++) ????cout<<"the result is "<<p[i]<<endl; ????return?0; } ? ????????? |
遇到問題:
1、使用swap()的時候,格式是:
#include <algorithm> using namespace std; swap(a,b);2、使用模板函數的時候,每一個模板函數都需要聲明template? <typename T> , 格式如下:
template <typename T> T Mysort(T a) //與一般函數用法相同 {return 2*a; }3、出錯解析:
?這四行加起來是一個錯誤,編譯器只不過在提示。
比如第一句是:在bubble函數的使用中
第二行解釋其中是因為Mysort需要使用這個函數
第三行如果我們點擊,提示出現在主函數中,是Mysort的使用的地方
第四行是真正的錯誤,也就是swap函數沒有定義
4、運行結果:
?
?上述算法就是sort()排序方法的一種實現原理
參考書籍:
1---《數據結構(C++語言版)》鄧俊輝
?
總結
以上是生活随笔為你收集整理的【转】C++学习四 冒泡排序法的一些改进的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用envi对landsat8数据进行处
- 下一篇: 【转】【C++学习笔记】C++异常处理