C++实现计数排序
2017-06-25 10:20
295 查看
计数排序首先利用数组计数器count[]对每个数字在数组data[]中出现的次数进行计数.然后,计数器将所有<=i的整数的个数添加并存储到count[i]中.通过这种办法,count[i]-1表明i在data[]中的主位置.
时间复杂度: 4*max value
空间复杂度: O(n),需要额外计数器存储与额外最终排序空间存储,即不是在原有数组上进行排序.
算法稳定性: 稳定
补充强化C++基础,const int * 与 int * const
const int * 指针指向的数组,数组的指针可以移动(++,–等),但数组的值不能被改动.
int* const 指针指向的数组,数组的指针不可以移动(++,–等),但数组的值可以改动.
C++ 代码如下:
头文件:
源文件:
时间复杂度: 4*max value
空间复杂度: O(n),需要额外计数器存储与额外最终排序空间存储,即不是在原有数组上进行排序.
算法稳定性: 稳定
补充强化C++基础,const int * 与 int * const
const int * 指针指向的数组,数组的指针可以移动(++,–等),但数组的值不能被改动.
int* const 指针指向的数组,数组的指针不可以移动(++,–等),但数组的值可以改动.
C++ 代码如下:
头文件:
void countSort(unsigned const int* sortArray);
源文件:
template <typename T, unsigned int size> void Sort<T, size>::countSort(unsigned const int* sortArray) { unsigned int *tmpArray = new unsigned int[size]; memset(tmpArray, 0, size*sizeof(unsigned int)); unsigned int max = 0; const unsigned int* startLoc = sortArray; //First loop, find out the max value, the max value will define count array element num for (unsigned int i = 0; i < size; i++) { loopTimes++; moveTimes++; unsigned int value = *sortArray; if (value > max) { max = value; } tmpArray[i] = value; if (i == size - 1) { } else { sortArray++; } } unsigned int* countArray = new unsigned int[max+1]; memset(countArray, 0, (max+1)*sizeof(unsigned int)); sortArray = startLoc; //Second loop, count every elem frequency for (unsigned int i = 0; i < size; i++) { loopTimes++; moveTimes++; unsigned int value = *sortArray; countArray[value]++; if (i == size - 1) { } else { sortArray++; } } unsigned int culValue = 0; //Third loop, count the elem num less and equal than each elem for (unsigned int i = 0; i < max + 1; i++) { loopTimes++; moveTimes++; culValue = culValue + countArray[i]; countArray[i] = culValue; } //Fourth loop, set the value into tmpArray for (unsigned int i = 0; i < size; i++) { loopTimes++; moveTimes++; unsigned int sortArrayTailValue = *sortArray; tmpArray[countArray[sortArrayTailValue] - 1] = sortArrayTailValue; countArray[sortArrayTailValue]--; sortArray--; } //print tmpArray, tmp Array is sorted list for (unsigned int i = 0; i < size; i++) { if ((i != 0) && (i % 8 == 0)) { cout << endl; } cout << tmpArray[i] << " "; } }
相关文章推荐
- C++实现计数排序
- C++ 计数排序的实现
- 直接查找排序,归并排序,快速排序,计数排序 ,堆排 C++实现
- 《算法导论》中的计数排序的C++实现
- C++实现计数排序
- C++实现计数排序
- 算法设计之计数排序 (C++实现)
- C++实现计数排序
- 计数排序及其C++实现
- 【算法导论】c++实现计数排序
- C++实现计数排序
- 计数排序(c++实现)
- 用 C++ 实现 C# 中的 委托/事件 (4-functor1)
- 在C++中实现“属性 (Property)”
- C++机理:虚拟机制的实现[兼谈对比于传统机制]
- 用C++ std::priority_queue 实现哈夫曼算法
- 用C++实现C#中的委托/事件(标准C++之升级版)
- 再探C++的单件实现
- 用 C++ 实现 C# 中的 委托/事件 (2-delegate event functor)
- 在C++中实现属性