高級冒泡排序-->用模板仿函數再次實現

#include<iostream>
using namespace std;
///////////////////////////使用模板類及仿函數來實現冒泡排序///////////////////////////////
template<typename T>
	class Great
	{
     public:
		bool operator()(T& left, T& right)//重載()
		{
			return left > right;
		}
	};
template<typename T>
	class Less
	{
     public:
		bool operator()(T& left, T& right)
		{
			return left < right;
		}
	};

template<typename T, typename Compare>
class Sort//定義一個排序的類
{
public:
	static void BubbleSort(T* arr, int size)
    {
	   bool flag = false;//設置標誌位
	   for(int i = 0;i < size - 1; i++)
	   {
		   flag = false;
		   for(int j = 0;j < size-i-1; ++j)
		   {
			   if(Compare()(arr[j], arr[j+1]))
			   {
				   std::swap(arr[j],arr[j+1]);
				   flag = true;
			   }
		   }
		   if(!flag)
		       break;//如果都沒有發生交換就跳出
	   }
    }
	static void Print(T* arr, size_t size)
	{
		for(int idx = 0; idx < size; idx++)
		{
			cout<<arr[idx]<<" ";
		}
		cout<<endl;
	}
};

int main()
{
	int arr[] = {2,4,1,3,66,33,5,8,22,7};
	Sort<int,Less<int>>::BubbleSort(arr,10);
	Sort<int,Less<int>>::Print(arr,10);
	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章