/************************************************************************/
/* 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的时间。测试发现,双向冒泡确实可以提高排序效率。