c++之排序(template)

#include <iostream>
using namespace std;


template<class T>
int Max(T& a,int n)
{
//取得数组最大元素的位置
int position  = 0;
for(int i = 0; i < n; ++i)
{
if (a[position] < a[i])
{
position = i;
}
}
return position;
}
template<class T> 
void Swap(T& a,T& b)//普通变量必须用引用或者指针,数组可以随便
{
T temp = a;
a = b;
b = temp;
}
template<class T> 
void SelectSort(T& a,int n)
{
for (int i = n; i > 0; --i)

//对数组a [ 0 : n-1 ]中的n个元素进行排序 
int position = Max(a,i);
Swap(a[position],a[i-1]);
}
}
template<class T> 
void Print(T& a,int n)
{
for (int i = 0; i < n; ++i)
{
cout << a[i];
cout << " ";
}
}
template <class T>


int getArrayLen(T& array)
{


return (sizeof(array) / sizeof(array[0]));


}
template <class T> 
void Bubble (T a[], int n) 

//把数组a [ 0 : n-1 ]中最大的元素通过冒泡移到右边 
   for ( int i = 0; i < n-1; i++)
   {
  if( a[i] > a[i +1]) 
  Swap(a[i], a[i+1]) ;
   }
}
template <class T> 
void BubbleSort (T a[], int n) 

//对数组a [ 0 : n-1 ]中的n个元素进行冒泡排序 
for (int i = n; i>1; --i)
{
Bubble(a,i);
}
}
template<class T>
void Insert(T a[],int n, int x)
{
int i;
for(i = n-1; i >= 0 && x < a[i]; --i)
{
a[i+1] = a[i];
}
a[i+1] = x;
}
template<class T>
void InsertSort(T a[], int n)
{
for(int i =1; i < n; ++i)
{
T x = a[i];
Insert(a,i,x);        
}
}


int main()
{
int a[] = {2,22,13,14,6,7,78,46,1,0};
int length = getArrayLen(a);
SelectSort(a,length);//选择排序
Print(a,length);
cout << endl;
BubbleSort(a,length);//冒泡排序
Print(a,length);
cout << endl;
InsertSort(a,length);//插入排序
Print(a,length);
system("PAUSE");
return 0;

}
练习c++,more exercise,more good!!!吐舌头




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值