zoukankan      html  css  js  c++  java
  • 用模板写插入排序-数组

        为了熟练模板的使用,今天,我们共同来写一个针对数组的插入排序算法,为了实现算法与数据类型相分离,我们这里采用函数模板的机制,具体如例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;
    }
    #endif
    main.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] << '	';
    	}
    	cout << endl;
    	if (InsertSort<int>(a, 10) == false)
    	{
    		cout << "排序失败." << endl;
    	}
    	else
    	{
    		cout << "排序后:" << endl;
    		for (i = 0; i < 10; i++)
    		{
    			cout << a[i] << '	';
    		}
    	}
    	cout << "排序前:" << endl;
    	for (i = 0; i < 10; i++)
    	{
    		cout << b[i] << '	';
    	}
    	cout << endl;
    	if (InsertSort<double>(b, 10) == false)
    	{
    		cout << "排序失败." << endl;
    	}
    	else
    	{
    		cout << "排序后:" << endl;
    		for (i = 0; i < 10; i++)
    		{
    			cout << b[i] << '	';
    		}
    	}
    	system("pause");
    	return;
    }
    运行效果如图1所示:


    图1 运行效果

        今天主要实现了数组的插入排序模板,希望大家回去实践一下,加深体会。

  • 相关阅读:
    20191010-2 每周例行报告
    2018092609-2 选题 Scrum立会报告+燃尽图 01
    20190919-1 每周例行报告
    20190919-4 单元测试,结对
    20190919-6 四则运算试题生成,结对
    20190919-5 代码规范,结对
    PSP总结报告
    20181204-1 每周例行报告
    每个成员明确公开地表示对成员帮助的感谢 (并且写在各自的博客里)
    作业要求 20181127-2 每周例行报告
  • 原文地址:https://www.cnblogs.com/new0801/p/6176955.html
Copyright © 2011-2022 走看看