排序算法
1 - 计数排序思想,假设对数组A[p...r]排序,其中数组中所有元素都为正整数,并且都是小于max_val:
* - 首先对A进行计数。对每一个元素A[i],将它出现的次数存放在CounterArray[A[i]]中
* - 然后对CounterArray累加,得出A[i]应该在结果序列中排多少位
* - 最后在结果数组中直接放置A[i](根据它的排位)
* - 时间复杂度 O(n)
* - 空间复杂度 O(n)
这里我们更多的使用泛型编程的思想,之所以用template是为了编写通用的代码,使程序用更好的可复用性,这也是c++编程提倡的理念,泛化类型。
template<typename Iterator> void count_sort(const Iterator begin,const Iterator end,const typename std::iterator_traits<Iterator>::value_type& max_val) { typedef typename std::iterator_traits<Iterator>::value_type T;// 迭代器指向对象的值类型 static_assert(std::is_integral<T>::value, "sequence to be sorted must be integer!"); //必须针对整数进行计数排序 auto size=std::distance(begin,end); if(size <=1) return; std::vector<T> CounterArray(max_val+1); //存放计数结果 std::vector<T> ResultArray(size); //暂存排序结果 std::size_t n=0; while(begin+n!=end) //计个数 { CounterArray.at(*(begin+n))++; n++; } for(std::size_t i=1;i<CounterArray.size();i++)//计排位数 { CounterArray.at(i)+=CounterArray.at(i-1); } int index=ResultArray.size()-1; while(index>=0) { auto data=*(begin+index); //待排序的元素 T less_data_num=CounterArray[data]-1; //比它小的元素的个数 ResultArray[less_data_num]=data; //直接定位 CounterArray[data]--; //此行为了防止重复元素的定位 index--; } std::copy(ResultArray.begin(),ResultArray.end(),begin); }
// 打印输出的函数模板
template<class T>
inline void PRINT_ELEMENTs(const T& coll,const char *optstr = "")
{
typename T::const_iterator pos;
std::cout << optcstr;
for(pos = coll.begin();pos!= coll.end();++pos)
{
std::cout << *pos << ' ';
}
std::cout << std::endl;
}
测试代码:
int main() { std::vector<int> comparedata{10,9,8,7,6}; count_sort(comparedata.begin(),comparedata.end(),10); PRINT_ELEMENTS(comparedata); }