Bootstrap

C++ 冒泡排序

今晚深信服笔试,重温一下排序题,顺便充当一下以后的轮子。
升序冒泡排序就是将数组从头到尾相邻数比较,大的换到后面,重复就可以得到所需排序结果。

非模板编程

#include<iostream>
using namespace std;
void bubbleSort(int a[], int n)
{
	if (n <= 1)//当数组元素个数小于2时,不需要排序。
		return;
	int temp;
	for (int i = 0; i < n-1; i++)
	{
		for (int j = 1; j < n-i; j++)
		{
			if (a[j] < a[j - 1])
			{
				temp = a[j];
				a[j] = a[j - 1];
				a[j - 1] = temp;
			}
		}
	}
}

int main()
{
	const int n = 5;
	int a[n] = { 3,-5,2,1,0 };
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;

	bubbleSort(a, n);
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	system("pause");
	return 0;

}

输出:
冒泡排序非模板编程

模板编程

#include<iostream>
using namespace std;

template<typename T>
void bubbleSort(T a[], int n)
{
	T temp;
	for (int i = 0; i < n-1; i++)
	{
		for (int j = 1; j < n-i; j++)
		{
			if (a[j] < a[j - 1])
			{
				temp = a[j];
				a[j] = a[j - 1];
				a[j - 1] = temp;
			}
		}
	}
}

int main()
{
	const int n = 5;
	float a[n] = { 3.2,-5.35,2.65,1.89,0.67 };
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;

	bubbleSort(a, n);
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
	system("pause");
	return 0;

}

输出:
冒泡排序模板编程

;