C++ 泛型编程:用函数模板做参数实现快排

C++ 泛型编程:用函数模板做参数实现快排

快排原理参考这篇博客:

https://blog.csdn.net/qq_28584889/article/details/88136498
(讲的很精髓,鞭辟入里)

利用函数模板实现泛型编程可以提供很大的方便

#include 
using namespace std;

template <typename T>
void myQuickSort(int left, int right, T* arr)
{
	if (left > right)
		return;
	T base, temp;
	int i, j;

	i = left, j = right;
	base = arr[left];//取最左边的数为基准数
	while (i < j)
	{
		while (arr[j] >= base && i < j)
			j--;
		while (arr[i] <= base && i < j)
			i++;
		if (i < j)
		{
			temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
		}
	}
	arr[left] = arr[i];//i = j
	arr[i] = base;//基准数归位

	myQuickSort(left, i - 1, arr);//递归左边
	myQuickSort(i + 1, right, arr);//递归右边
}

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

//让我们来测试一下吧
int main()
{
	char arrChar[] = { 'b','c','d','a','f','e','h','g','i' };
	int arrInt[] = { 4,2,5,2,6,1,67,4,7,3,7,9 };

	int rightChar = sizeof(arrChar) / sizeof(arrChar[0]) - 1;
	int rightInt = sizeof(arrInt) / sizeof(arrInt[0]) - 1;

	myQuickSort(0, rightChar, arrChar);
	myPrint(arrChar, rightChar + 1);

	myQuickSort(0, rightInt, arrInt);
	myPrint(arrInt, rightInt + 1);

	return 0;
}

运行结果

a b c d e f g h i
1 2 2 3 4 4 5 6 7 7 9 67

你可能感兴趣的:(C++)