1 #include<iostream> 2 3 using namespace std; 4 5 template<class T>//函数模板 应对多种类型的变量 6 void InseartionSort(T *p, int n); 7 8 int main() 9 { 10 double a[] = { 2,4,6.5,8,1,3.8,5,7.4,9,0 }; 11 InseartionSort(a, 10); 12 for (int i = 0; i < 10; i++) 13 cout << a[i]<<endl; 14 system("pause"); 15 return 0; 16 17 } 18 template<class T> 19 void InseartionSort(T *p, int n) 20 { 21 int in, out; 22 //out=0已经排好 23 for (out = 1; out < n; ++out)//++out与out++一样 24 { 25 T temp = p[out]; 26 in = out; 27 while( p[in - 1] >= temp) 28 { 29 p[in] = p[in - 1]; 30 --in;//--in与in--一样 31 } 32 p[in] = temp; 33 } 34 }
运行结果: