C++——演算法基礎之排序——氣泡排序(優化)
阿新 • • 發佈:2019-02-06
今天,大白跟大家聊一聊氣泡排序的優化,我們都知道氣泡排序是幾種穩定排序中比較快的一種排序了。
但是,演算法的優化永無止境,革命尚未成功,“同志”仍須努力(嘻嘻)。
今天大白再看了教科書之後,並且融入了一些自己的想法,使得氣泡排序更加優化了。
首先,我們來看一組圖:
bubbleSortText:
bubbleSort:
下面我們來看看程式碼實現及執行結果:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <functional> #include <algorithm> #include <numeric> #include <stack> #include <queue> #include <vector> #include <string> #include <cstring> #include <time.h> using namespace std; //原始氣泡排序 void bubbleSortOriginal (int *a, int n, int flag, int time) { for(int i = 1; i < n; i++) { for(int j = 0; j < n - i; j++) { time++; if(a[j] > a[j + 1]) { flag++; int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } cout << "bubbleSortOriginal排序總共進行了 " << flag << " 次交換和 " << time << " 次迴圈" << endl; } //氣泡排序優化一 void bubbleSortText (int *a, int n, int flag, int time) { bool completeSort = false; for(int i = 1; i < n && (!completeSort); i++) { completeSort = true; //如果在一次內迴圈中,一次交換都沒有進行,則此時排序已完成,可以退出 for(int j = 0; j < n - i; j++) { time++; if(a[j] > a[j + 1]) { flag++; int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; completeSort = false; } } } cout << "bubbleSortText排序總共進行了 " << flag << " 次交換和 " << time << " 次迴圈" << endl; } //氣泡排序優化二 void bubbleSort (int *a, int n, int flag, int time) { bool completeSort = false; bool getTwoMax = false; for(int i = 1; i < n && (!completeSort); i++) { completeSort = true; for(int j = 0; j < n - i; j++) { time++; getTwoMax = true; //如果在一次內迴圈中,最後一次交換沒有進行,則外迴圈可以少進行一次 if(a[j] > a[j + 1]) { flag++; int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; completeSort = false; getTwoMax = false; } } if(getTwoMax) { i++; } } cout << "bubbleSort排序總共進行了 " << flag << " 次交換和 " << time << " 次迴圈" << endl; } int main () { int flag1 = 0, flag2 = 0, time1 = 0, time2 = 0; //falg標記交換進行的次數,time標記迴圈進行的次數 int a1[] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int a2[] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int a3[] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; bubbleSortOriginal (a1, 10, flag1, time1); for(int i = 0; i < 10; i++) { cout << " " << a1[i]; } cout << endl; bubbleSortText (a2, 10, flag1, time1); for(int i = 0; i < 10; i++) { cout << " " << a2[i]; } cout << endl; bubbleSort (a3, 10, flag2, time2); for(int i = 0; i < 10; i++) { cout << " " << a3[i]; } cout << endl; return 0; }