现在的位置: 首页 > 综合 > 正文

C++冒泡排序模板

2013年02月16日 ⁄ 综合 ⁄ 共 1199字 ⁄ 字号 评论关闭

template<typename T>
void print(T *array,const int size)
{
	if(NULL==array)
		throw;
    
	if(0>=size)
		return;
    
	int i=0;
	for(;i<size;++i)
		cout<<array[i]<<" ";
	cout<<endl;
}

template<typename T>
void bubble_sort(T *array,const int size)
{
	if(NULL==array)
		throw;
    
	if(0>=size)
		return;
    
	int i=0;
	int j=0;
	T temp;
	for(;i<size-1;++i)
	{
		for(j=0;j<size-i-1;++j)
		{
			if(array[j]>array[j+1])
			{
                //			array[j]=array[j]+array[j+1]-(array[j+1]=array[j]);
				temp=array[j];
				array[j]=array[j+1];
				array[j+1]=temp;
			}
		}
	}
}

int main(int argc, const char * argv[])
{
    
    int a[]={4,1,2,5,3};
	const int size_a=sizeof(a)/sizeof(a[0]);
    
	double b[]={1.11111,3.33333,2.22222};
	const int size_b=sizeof(b)/sizeof(b[0]);
    
	char c[]="CDmnopEFGhijABklq";
	const int size_c=strlen(c);
    
	string d[]={"bbb","aaa","ccc","ddd"};
	const int size_d=sizeof(d)/sizeof(d[0]);
    
	cout<<"原始数据"<<endl;
	print(a,size_a);
	print(b,size_b);
	print(c,size_c);
	print(d,size_d);
    
	bubble_sort(a,size_a);
	bubble_sort(b,size_b);
	bubble_sort(c,size_c);
	bubble_sort(d,size_d);
    
	cout<<endl<<"经通用冒泡排序函数排序后"<<endl;
	print(a,size_a);
	print(b,size_b);
	print(c,size_c);
	print(d,size_d);
  
    return 0;
}





/*---------------------
 原始数据
 4 1 2 5 3
 1.11111 3.33333 2.22222
 C D m n o p E F G h i j A B k l q
 bbb aaa ccc ddd
 
 经通用冒泡排序函数排序后
 1 2 3 4 5
 1.11111 2.22222 3.33333
 A B C D E F G h i j k l m n o p q
 aaa bbb ccc ddd
 Press any key to continue
 ------------------------*/

抱歉!评论已关闭.