冒泡排序C++模板实现

冒泡排序C++模板实现

#include <iostream>
#include <stdio.h>

using namespace std;

//冒泡排序
template <class T>
void BubSort(T *begin, T *end)
{
	T *pi, *pj;
	for (pi = end; pi > begin; pi--)
		for (pj = begin + 1; pj < pi; pj++)
			if (*(pj - 1) > *pj)
			{
				//交换数据
				T temp;
				temp = *(pj - 1);
				*(pj - 1) = *pj;
				*pj = temp;
			}
}

//改进的冒泡排序
template <class T>
void BubbleSort(T *begin, T *end)
{
	T *pi, *pj;
	
	int exchange = 0;//记录每次扫描时是否发生交换
	
	for (pi = end; pi > begin; pi--)
	{	
		exchange = 0;//每次扫描前置0
		
		for (pj = begin + 1; pj < pi; pj++)
		{
			if (*(pj - 1) > *pj)
			{
				//交换数据
				T temp;
				temp = *(pj - 1);
				*(pj - 1) = *pj;
				*pj = temp;
				
				exchange = 1;//发生交换设置为1
			}
		}
		
		if (exchange != 1)//此趟扫描没有发生过交换,说明已经是排序的,不需要进行下次扫描
			return;
	}
}

int main()
{
	int a[5] = {3,6,8,4,9};
	float b[5] = {1.2, 0.2, 56.3, 11.2, 12.6};
	
	//BubSort(a, a + 5);
	//BubSort(b, b + 5);
	
	BubbleSort(a, a + 5);
	BubbleSort(b, b + 5);
	
	for (int i = 0; i < 5; i++)
		cout << a[i] << "\t";
	
	cout << endl;
	
	for (int i = 0; i < 5; i++)
		cout << b[i] << "\t";
		
	getchar();
		
	return 0;
}

输出:

3       4       6       8       9
0.2     1.2     11.2    12.6    56.3



你可能感兴趣的:(冒泡排序C++模板实现)