练练手:将之前写的冒泡排序改成函数模版实现

整个排序设计三个步骤:获取数组信息,排序,输出排好序的数组内容

分别写成三个函数模版

获取数组信息

template <typename T>
void get(T *array, int LEN)
{
	for(int i = 0 ; i < LEN; i++)
	{
		cin >> array[i];
	}
}

排序

template <typename T>
void sort(T *array, int LEN)
{
	T tmp;
	for(int i = 0; i < LEN - 1; i++ )
	{
		for(int j = 0; j < LEN -1 -i; j++)
		{
			if(array[j] > array[j+1])
			{
				tmp = array[j];
				array[j] = array[j + 1];
				array[j+1] = tmp;
			}
		}
	}
}

输出排好序的数组内容

template <typename T>
void put(T *array, int LEN)
{
	for(int i = 0; i < LEN; i++)
	{
		cout << array[i] << " ";
	}
	cout << endl;
}

至此完成

猜你喜欢

转载自blog.csdn.net/userkiller/article/details/81346834