欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于函数指针做函数参数的运用(冒泡排序)

程序员文章站 2022-07-15 09:33:53
...
/*
@OndO 
练习
利用函数指针做函数参数进行冒泡排序
参考:
https://zhuanlan.zhihu.com/p/37306637
*/
using namespace std;
#include <iostream>

//创建函数模板
template <typename T>
bool foo(const T a, const T b)
{
	return (a < b);
}
template <typename T>
bool foo_1(const T i, const T j)
{
	return (i > j);
}

template <typename T>
void Sort_foo(T a[], int len, bool (*func)(T, T))
{
	bool choice = false;
	while (!choice)
	{
		choice = true;
		for (int s = 0; s < len - 1; s++)
		{
			if (func(a[s], a[s + 1]))
			{
				swap(a[s], a[s + 1]);
				choice = false;
			}
		}
		len--;
	}
}

int main(void)
{
	int array[] = { 13,2,12,41,23,12,4,11,14,131,4 };
	int l = sizeof(array) / sizeof(int);
	Sort_foo<int>(array, l, foo<int>);
	for (int num : array)
	{
		cout << num << endl;
	}
	return 0;
}