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 运行效果

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

  • 相关阅读:
    MVC CONTROLS TOOLKIT
    activemq Example
    OWASP
    ActiveMQ持久化消息的三种方式
    sqlyog
    dotnet压缩
    asp.net ajax 环境 c#与js互调
    asp.net 初步入门使用正则抓取网页信息
    用ASP.NET with C# 绘制曲线图(Curve图)转
    asp.net 中使用excel组件权限设置
  • 原文地址:https://www.cnblogs.com/new0801/p/6176955.html
Copyright © 2011-2022 走看看