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

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

  • 相关阅读:
    友盟上报 IOS
    UTF8编码
    Hill加密算法
    Base64编码
    Logistic Regression 算法向量化实现及心得
    152. Maximum Product Subarray(中等, 神奇的 swap)
    216. Combination Sum III(medium, backtrack, 本类问题做的最快的一次)
    77. Combinations(medium, backtrack, 重要, 弄了1小时)
    47. Permutations II(medium, backtrack, 重要, 条件较难思考)
    3.5 find() 判断是否存在某元素
  • 原文地址:https://www.cnblogs.com/new0801/p/6176955.html
Copyright © 2011-2022 走看看