计数排序,基数排序

计数排序(CountingSort)

#ifndef COUNTINGSORT_H #define COUNTINGSORT_H /** * @brief Counting sort the array "from" to array "to", from small to large. The complexity is O(n + k). This method applies to such situation: * the n elements in the array are integers and the range of the integers is 0 to k * * @tparam T: template type * @param from: the array to be sorted, index from 1 to n * @param to: the sorted array, namely output array, index from 1 to n * @param k: the scope of the integers * @param n: the number of elements in the array */ template <typename T> void CountingSort(T *from, T *to, int k, int n) { //count[i] means the number of elements who is not larger than i int *count = new int[k + 1]; for (int i = 0; i <= k; ++i) { count[i] = 0; } for (int i = 1; i <= n; ++i) { count[from[i]]++; } for (int i = 1; i <= k; ++i) { count[i] += count[i - 1]; } for (int i = n; i > 0; --i) { to[count[from[i]]] = from[i]; count[from[i]]--; } delete[] count; } #endif /* end of include guard: COUNTINGSORT_H */

应用场景:排序n个数,数的范围从0到k。

 

 

 

基数排序(RadixSort)

应用场景:对n个d位k进制数进行排序。

算法思想:在每一位上进行基数排序,从低位开始。

算法复杂度:O(d*(n + k))。

你可能感兴趣的:(算法,delete,include,output)