C++STL之希尔排序

2015-04-03 0 342
C++STL之希尔排序
/*****************************
*shellSort.h
*****************************/
#include "stdafx.h"
#include <vector>
 
using namespace std;
 
template <typename T>
void shellSort(vector<T>& vec)
{
    int gap = vec.size()/2;
    for (; gap != 0; gap = gap/2)
    {
        shellSort(vec, gap); //以gap步长为参数进行排序
    }
}
template <typename T>
void shellSort(vector<T>& vec, int gap)
{
    int i = gap;
    for (; i < vec.size(); i++) // 从gap 到 vec.size()之间
    {
        //这种循环交换的思想,省去每次比较都要交换的次数
        T tempValue = vec[i];
        int j = i;
        for (; j >= gap && tempValue < vec[j - gap] ; j = j - gap) //这里其实进行的是倒序循环
        {
            vec[j] = vec[j - gap];
        }
        vec[j] = tempValue;
    }
}

遇见资源网 c/c++ C++STL之希尔排序 http://www.ox520.com/10034.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务