Linux学习笔记----用模板:template<class T>void sort(T *a,int n,bool f),对一维数组a进行排序,f为1从小到大排序,f为0从大到小排序(使用快排)

模板:swp函数是用来交换数组里面的两个元素,Quicksort_low函数,将数组进行从小到大排序

Quicksort_high函数,将数组进行从大到小排序

以下是实现题目要求的代码:

#include "iostream"
using namespace std;
template<class T> void swp(T& a, T& b)
{
	T temp;
	temp = a;
	a = b;
	b = temp;
}
template <class T> void Quicksort_low(T* a, int l, int r) {
	if (l >= r) return;
	int i = l, j = r;
	int key = l;
	while (j > i) {
		while (j > i && a[j] >= a[key])
			j--;
		while (j > i && a[i] <= a[key])
			i++;
		/*int temp;
		temp = a[i];
		a[i] = a[j];
		a[j] = temp;*/
		swp(a[i], a[j]);

	}
	/*int temp;
	temp = a[key];
	a[key] = a[i];
	a[i] = temp;*/
	swp(a[i], a[key]);
	Quicksort_low(a, l, i - 1), Quicksort_low(a, i + 1, r);
}

template <class T> void Quicksort_high(T* a, int l, int r) {
	if (l >= r) return;
	int i = l, j = r;
	int key = l;
	while (j > i) {
		while (j > i && a[j] <= a[key])
			j--;
		while (j > i && a[i] >= a[key])
			i++;
		/*int temp;
		temp = a[i];
		a[i] = a[j];
		a[j] = temp;*/
		swp(a[i], a[j]);

	}
	/*int temp;
	temp = a[key];
	a[key] = a[i];
	a[i] = temp;*/
	swp(a[i], a[key]);
	Quicksort_high(a, l, i - 1), Quicksort_high(a, i + 1, r);
}
template<class T> void sort(T* a, int n, bool f)
{
	if (f == 1)//从小到大排序
	{
		Quicksort_low(a, 0, n-1);
	}
	if (f == 0)//从大到小排序
	{
		Quicksort_high(a, 0, n-1);
	}
}

int main()
{
	int arr[5] = { 3,1,2,6,5 };
	sort(arr, 5, 1);
	cout << "排序后:" << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << arr[i] << endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值