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

        今天,我们一起来写选择排序,主要是熟悉模板编程,具体如例1所示。

    例1 选择排序-数组

    SelectSort.hpp内容:

    #ifndef _SELECT_SORT_H_
    #define _SELECT_SORT_H_
    template<typename T>
    bool SelectSort(T * pInput, int nLen)
    {
    	int i = 0;
    	int j = 0;
    	int nMin = 0;
    	T tTemp;
    	if (!pInput)
    		return false;
    	for (i = 0; i < nLen; i++)
    	{
    		nMin = i;
    		for (j = i + 1; j < nLen; j++)
    		{
    			if (pInput[j] < pInput[nMin])
    			{
    				nMin = j;
    			}
    		}
    		if (nMin != i)
    		{
    			tTemp = pInput[i];
    			pInput[i] = pInput[nMin];
    			pInput[nMin] = tTemp;
    		}
    	}
    	return true;
    }
    #endif
    main.cpp的内容:

    #include "SelectSort.hpp"
    #include <iostream>
    using namespace std;
    
    void main()
    {
    	int i = 0;
    	int a[10] = { 1, 4, 7, 2, 5, 8, 3, 6, 9, 0 };
    	cout << "排序前:" << endl;
    	for (i = 0; i < 10; i++)
    	{
    		cout << a[i] << '	';
    	}
    	cout << endl;
    	if (SelectSort<int>(a, 1) == false)
    	{
    		cout << "排序失败." << endl;
    	}
    	else
    	{
    		cout << "排序后:" << endl;
    		for (i = 0; i < 10; i++)
    		{
    			cout << a[i] << '	';
    		}
    	}
    	system("pause");
    	return;
    }
    运行效果如图1所示:

    图1 运行效果

        今天,我们一起完成了选择排序,希望对家回去实践一下,加深体会。


  • 相关阅读:
    nginx 限流配置
    redis-sentinel 高可用方案实践
    redis之 主从复制和哨兵
    MySQL架构与业务总结图
    MGR实现分析
    通过 SCQA 的框架来讲故事
    MECE分析法
    如何提高问题的认知高度
    Mac 应用程序不能打开解决方法
    vscode打开文件在同一个tab的问题
  • 原文地址:https://www.cnblogs.com/new0801/p/6176951.html
Copyright © 2011-2022 走看看