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

        今天,我们一起来写一个冒泡排序,仍然使用模板。

    例1 用模板写冒泡排序-数组

    ArrayBubbleSort.hpp内容:

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

    #include "ArrayBubbleSort.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 (BubbleSort<int>(a, 10) == false)
    	{
    		cout << "排序失败." << endl;
    	}
    	cout << "排序后:" << endl;
    	for (i = 0; i < 10; i++)
    	{
    		cout << a[i] << "	";
    	}
    	cout << endl;
    	system("pause");
    	return;
    }
    运行效果如图1所示:

    图1 运行效果

        今天,我们一起完成了冒泡排序,希望大家多实践。

  • 相关阅读:
    4.文本规范化处理
    2.自动文本分类
    3.文本分类的蓝图
    1.什么是文本分类
    2.文本规范化
    Python 处理和理解文本
    1.文本切分
    验证码识别
    随机函数
    Java编程思想笔记(多态)
  • 原文地址:https://www.cnblogs.com/new0801/p/6176953.html
Copyright © 2011-2022 走看看