您的位置:首页 > 其它

2011 4-25 计数排序

2011-04-26 10:31 197 查看
#pragma once



#include <iostream>

// #include <utility>

using std::cout;

using std::endl;

using std::pair;



template<typename value_type>

void counterSortImp(const value_type *const array, const pair<value_type, value_type> &scope, size_t size) {

// Firstly, calculate the count of any kind in the scope

size_t difference = scope.second - scope.first;

int *collection = new int[difference]();

for (size_t i=0; i<size; ++i)

{

int index = array[i] - scope.first;

++collection[index];

}



// Get the index of every kind of value_type

for (int i=1; i<difference; ++i)

{

collection[i] += collection[i-1];

}



// Sort the result into sorted array

value_type *sorted = new value_type[size]();

for (int i=size-1; i>=0; --i)

{

int index = array[i] - scope.first;

sorted[collection[index]-1] = array[i];

--collection[index];

}



// if you need, copy sorted to array by your self.

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: