漫画算法笔记 冒泡排序

漫画算法笔记

冒泡排序

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <iterator>
using namespace std;

//冒泡排序
template<typename T>
void bubbleSort1(vector<T> &vec)
{
	for ( int i = 0; i < vec.size() - 1; ++i )
	{
		for ( int j = 0; j < vec.size() - i - 1; ++j )
		{
			if ( vec[j] > vec[j + 1] ) 
			{
				using namespace std;
				swap(vec[j], vec[j + 1]);
			}
		}
	}
}

//冒泡排序第二版,没有元素交换没必要重排
template<typename T>
void bubbleSort2(vector<T> &vec)
{
	for (int i = 0; i < vec.size() - 1; ++i)
	{
		bool isSorted = true;
		for (int j = 0; j < vec.size() - i - 1; ++j)
		{
			if (vec[j] > vec[j + 1])
			{
				using namespace std;
				swap(vec[j], vec[j + 1]);
				isSorted = false;
			}
		}
		if (isSorted)
		{
			break;
		}
	}
}

//冒泡排序第三版,有序区没必要重排
template<typename T>
void bubbleSort3(vector<T> &vec)
{
	//记录最后一次交换的位置
	int lastExchangeIndex = 0;
	//无序数据的边界,每次比较只需要比到这里为止
	int sortBorder = vec.size() - 1;
	for (int i = 0; i < vec.size() - 1; ++i)
	{
		bool isSorted = true;
		for (int j = 0; j < sortBorder; ++j)
		{
			if (vec[j] > vec[j + 1])
			{
				using namespace std;
				swap(vec[j], vec[j + 1]);
				isSorted = false;
				lastExchangeIndex = j;
			}
		}
		sortBorder = lastExchangeIndex;
		if (isSorted)
		{
			break;
		}
	}
}

//鸡尾酒排序
template<typename T>
void sort(vector<T> &vec)
{
	for ( int i = 0; i < vec.size() / 2; ++i)
	{
		bool isSorted = true;
		//奇数轮,从左向右比较和交换
		for ( int j = i; j < vec.size() - i - 1; ++j )
		{
			if ( vec[j] > vec[j + 1] )
			{
				using namespace std;
				swap(vec[j], vec[j + 1]);
				isSorted = false;
			}
		}
		if (isSorted)
		{
			break;
		}

		//在偶数轮前,将isSorted重新标记为true
		isSorted = true;
		for (int j = vec.size() - i - 1; j > i ; --j)
		{
			if (vec[j] < vec[j - 1])
			{
				using namespace std;
				swap(vec[j], vec[j - 1]);
				isSorted = false;
			}
		}
		if (isSorted)
		{
			break;
		}
	}
}

void test01()
{
	vector<int> vec = { 5, 8, 6, 3, 9, 2, 1, 7 };
	//bubbleSort1(vec);
	//bubbleSort2(vec);
	bubbleSort3(vec);

	std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
	cout << endl;
}

void test02()
{
	vector<int> vec = { 2, 3, 4, 5, 6, 7, 8, 1 };
	sort(vec);

	std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
	cout << endl;
}

int main(int argc, char** argv)
{
	//test01();
	test02();

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值