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

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

  • 相关阅读:
    怎样修改原型对象prototype
    怎样获取构造函数的名字
    怎样把实例对象当构造函数用
    怎样理解prototype对象的constructor属性
    怎样理解构造函数的原型对象prototype
    怎样给回调函数绑定this
    怎样绑定this
    怎样理解数组的空元素empty与undefined的区别
    怎样找出数组中的最大数值
    怎样调用对象的原生方法
  • 原文地址:https://www.cnblogs.com/new0801/p/6176955.html
Copyright © 2011-2022 走看看