单向冒泡和双向冒泡排序算法

来源:互联网 发布:斗罗大陆3龙王传说淘宝 编辑:程序博客网 时间:2024/05/17 04:17

/************************************************************************//* 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 highfor (int i = low; i < high-1; i++){if (numbers[i] > numbers[i+1]){Swap(numbers[i], numbers[i+1]);count++;}}//Bubble to lowfor (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的时间。测试发现,双向冒泡确实可以提高排序效率。

0 0