• 用模板写快速排序-数组


        今天,我们继续用模板写代码,不断加深模板的熟练程度,今天,我们一起来写一个快速排序,具体如例1所示:

    例1 快速排序-数组

    ArrayQuickSort.hpp内容:

    #ifndef _ARRAY_QUICK_SORT_H_
    #define _ARRAY_QUICK_SORT_H_
    template<typename T>
    bool QuickSort(T * pInput, int nStart, int nEnd)
    {
    	int nLow = nStart;
    	int nHigh = nEnd;
    	T tKey = pInput[nStart];
    	if (!pInput)
    		return false;
    	if (nStart >= nEnd)
    		return true;
    	while (nLow < nHigh)
    	{
    		while (nLow < nHigh && pInput[nHigh] > tKey)
    		{
    			nHigh--;
    		}
    		if (nLow >= nHigh)
    			break;
    		pInput[nLow] = pInput[nHigh];
    		nLow++;
    		while (nLow < nHigh && pInput[nLow] <= tKey)
    		{
    			nLow++;
    		}
    		if (nLow >= nHigh)
    			break;
    		pInput[nHigh] = pInput[nLow];
    		nHigh--;
    	}
    	pInput[nLow] = tKey;
    	return QuickSort<T>(pInput, nStart, nLow-1) && QuickSort<T>(pInput,nLow+1, nEnd);
    }
    #endif
    main.cpp内容:

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

    图1 运行效果

        今天,我们共同完成了快速排序,希望大家回去多实践,熟练模板的使用。

  • 相关阅读:
    cds.data:=dsp.data赋值有时会出现AV错误剖析
    iOS -- 十进制、十六进制字符串,byte,data等之间的转换
    iOS -- 原生NSStream实现socket
    CA认证原理以及实现(下)
    CA认证原理以及实现(上)
    android -- 存储byte
    iOS -- 字符串(NSString *)转uint8_t的两种方法
    Android -- AsyncTask 使用和缺陷
    Swift oc 混编
    Android -- native关键字
  • 原文地址:https://www.cnblogs.com/new0801/p/6176949.html
Copyright © 2020-2023  润新知