單向冒泡和雙向氣泡排序演算法
阿新 • • 發佈:2019-01-10
/************************************************************************/ /* Bubble Sort */ /************************************************************************/ #include <iostream> #include <time.h> #include "Timer.h" using namespace std; #define Swap(x, y) {int temp = x; x = y; y = temp;} const int MAX = 100000; void Input(int* numbers) { srand((unsigned)time(NULL)); for (int i = 0; i < MAX; i++) { numbers[i] = rand() % (MAX * 10); } } void Output(int* numbers) { for (int i = 1; i <= MAX; i++) { cout << numbers[i-1] << " "; if (0 == i % 10) { cout << endl; } } cout << endl; } void BubbleSort(int* numbers) { for (int i = 0; i < MAX; i++) { int count = 0; //cout << "Bubbling : " << i << endl; for (int j = 0; j < MAX-1; j++) { //cout << numbers[j] << " "; if (numbers[j] > numbers[j+1]) { int temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; count++; } } //cout << numbers[MAX-1] << " "; //cout << "Bubble after: " << endl; //Output(numbers); if (0 == count) { break; } } } //雙向冒泡 void BubbleSort(int* numbers, int low, int high) { int count = 0; while (low < high) { count = 0; //Bubble to high for (int i = low; i < high-1; i++) { if (numbers[i] > numbers[i+1]) { Swap(numbers[i], numbers[i+1]); count++; } } //Bubble to low for (int i = high-1; i > low; i--) { if (numbers[i] < numbers[i-1]) { Swap(numbers[i], numbers[i-1]); count++; } } if (0 == count) { break; } low++; high--; } } void main() { int num[MAX]; Input(num); cout << "Bubble before: " << endl; //Output(num); Timer timer; //BubbleSort(num, 0, MAX); BubbleSort(num); cout <<"Time Elapsed: " << timer.GetElapsedTime() << "s" << endl; cout << "Bubble after: " << endl; //Output(num); }
單向氣泡排序結果如下:
雙向氣泡排序結果如下:
用10萬個int資料對兩個冒泡演算法進行測試,測試結果:單向冒泡平均需要60s的時間,而雙向冒泡平均需要30s的時間。測試發現,雙向冒泡確實可以提高排序效率。