10-1、(**) 排序函数模板

已知主函数如程序后缀代码所示,请为其编写适当的模板函数,使主函数的bubbleSort函数可以对一个整型数组和一个浮点数数组进行输入、排序、输出操作。

#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;

template <typename T>
T bubbleSort(T *p,const int arraySize)
{
    sort(p,p+arraySize);
    return *p;//p表示地址,*p表示访问地址获得变量 
}
//StudybarCommentBegin
int main()
{ 
   const int arraySize = 10;  // size of array
   int a[ arraySize ] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }, i;

   // display int array in original order
   cout << "Integer data items in original order\n";

   for ( i = 0; i < arraySize; ++i )
      cout << setw( 6 ) << a[ i ];

   bubbleSort( a, arraySize );          // sort the array

   // display int array in sorted order
   cout << "\nInteger data items in ascending order\n";

   for ( i = 0; i < arraySize; ++i )
      cout << setw( 6 ) << a[ i ];

   cout << "\n\n";

   // initialize double array
   double b[ arraySize ] = { 10.1, 9.9, 8.8, 7.7, 6.6, 5.5,
                            4.4, 3.3, 2.2, 1.1 };
   
   // display double array in original order								 
   cout << "double point data items in original order\n";

   for ( i = 0; i < arraySize; ++i )
      cout << setw( 6 ) << b[ i ];

   bubbleSort( b, arraySize );          // sort the array
   
   // display sorted double array
   cout << "\ndouble point data items in ascending order\n";

   for ( i = 0; i < arraySize; ++i )
      cout << setw( 6 ) << b[ i ];

   cout << endl;

   return 0;

} // end main
//StudybarCommentEnd

-END

posted @ 2023-04-22 14:47  找回那所有、  阅读(99)  评论(0)    收藏  举报
这里到底了哦~(●'◡'●)