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

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值