氣泡排序 C++版
阿新 • • 發佈:2018-12-19
一、說明:氣泡排序的原理在註釋中,文中氣泡排序使用了模板來傳入資料,詳細情況看下面的測試程式碼。
二、測試程式碼
#include <iostream> #include <vector> using namespace std; /****************************** 氣泡排序:從陣列的右到左對陣列進行兩兩比較排序,大的放到最右邊。 第一遍比較後最小的元素在最左邊的0號位置,第二遍開始將第2小的數 據放到1號位置,一直比較到只剩最後兩個元素確認是否交換為止。 優點:1、簡單 缺點:1、在各種情況下的比較次數都相等,效率低 演算法複雜度:O(n~n^2) 空間複雜度:O(1) ******************************/ // 實現方法一 template<typename T> void bubbleSort1(T data[], int n) { for(int i=0; i<n-1; i++) { for(int j=n-1; j>i; j--) { if(data[j]<data[j-1]) { T temp = data[j]; data[j] = data[j-1]; data[j-1] = temp; } } } } // 實現方法二冒泡改進版 template<typename T> void bubbleSort2(T data[], int n) { // 設定標誌位用來檢視是否發生交換,如果沒有發生交換說明排序已經完成,不需要再進行排序 // 這種情況發生的概率不多,這種改進需要額外儲存一個變數,效果可能還不如第一種效果好 bool flag = true; for(int i=0; i<n-1 && flag; i++) { flag = false; for(int j=n-1; j>i; j--) { if(data[j]<data[j-1]) { T temp = data[j]; data[j] = data[j-1]; data[j-1] = temp; flag = true; } } } } // 實現方法三 template<typename T> void bubbleSort3(vector<T> &data) { for(int i=0; i<data.size()-1; i++) { for(int j=data.size()-1; j>i; j--) { if(data[j] < data[j-1]) { T temp = data[j]; data[j] = data[j-1]; data[j-1] = temp; } } } } int main() { int tempArr[] = {0,4,3,5,6,7,9,8,2,1}; int arrSize = sizeof(tempArr)/sizeof(tempArr[0]); cout << "arrSize=" << arrSize << endl; // bubbleSort1 test // bubbleSort1(tempArr,arrSize); // bubbleSort2(tempArr,arrSize); vector<int> tempVec(tempArr,tempArr+arrSize); bubbleSort3(tempVec); cout << "===========bubbleSort tempArr==========" << endl; for(int i=0; i<arrSize; i++) { cout << tempArr[i] << endl; } cout << "===========bubbleSort tempVec==========" << endl; for(int i=0; i<arrSize; i++) { cout << tempVec[i] << endl; } cout << "Hello World!" << endl; return 0; }
三、測試結果