用模板写插入排序-数组
为了熟练模板的使用,今天,我们共同来写一个针对数组的插入排序算法,为了实现算法与数据类型相分离,我们这里采用函数模板的机制,具体如例1所示。
例1 数组插入排序
ArrayInsertSort.hpp内容:
#ifndef _ARRAY_INSERT_SORT_H_ #define _ARRAY_INSERT_SORT_H_ template<typename T> bool InsertSort(T * pInput, int nLen) { int i = 0; int j = 0; T tTemp; if (!pInput) return false; for (i = 1; i < nLen; i++) { tTemp = pInput[i]; for (j = i - 1; (j >= 0) && (pInput[j] > tTemp); j--) { pInput[j + 1] = pInput[j]; } pInput[j + 1] = tTemp; } return true; } #endifmain.cpp内容:
#include "ArrayInsertSort.hpp" #include <iostream> using namespace std; void main() { int i = 0; int a[10] = { 1,4,7,2,5,8,3,6,9,0 }; double b[10] = { 1.1, 4.4, 7.7, 2.2, 5, 8.8, 3, 6, 9.9, 0 }; cout << "排序前:" << endl; for (i = 0; i < 10; i++) { cout << a[i] << '\t'; } cout << endl; if (InsertSort<int>(a, 10) == false) { cout << "排序失败." << endl; } else { cout << "排序后:" << endl; for (i = 0; i < 10; i++) { cout << a[i] << '\t'; } } cout << "排序前:" << endl; for (i = 0; i < 10; i++) { cout << b[i] << '\t'; } cout << endl; if (InsertSort<double>(b, 10) == false) { cout << "排序失败." << endl; } else { cout << "排序后:" << endl; for (i = 0; i < 10; i++) { cout << b[i] << '\t'; } } system("pause"); return; }运行效果如图1所示:
图1 运行效果
今天主要实现了数组的插入排序模板,希望大家回去实践一下,加深体会。