C++实现计数排序
来源:互联网 发布:华为相机软件下载 编辑:程序博客网 时间:2024/06/16 02:53
计数排序首先利用数组计数器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++ 代码如下:
头文件:
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] << " "; }}
阅读全文
0 0
- 计数排序C实现
- 计数排序c/c++实现
- 计数排序C语言实现
- 计数排序-C语言实现
- C数据结构---计数排序实现
- 计数排序算法实现(C版)
- 计数排序算法(C语言实现)
- 算法导论C语言实现: 计数排序
- 计数排序的C语言实现
- 计数排序及C语言实现
- 计数排序C++实现
- 算法导论计数排序实现(C++)
- 计数排序(c#)
- 计数排序C语言
- 【C++】计数排序
- 计数排序(C语言版)
- 计数排序的实现
- 计数排序简单实现
- #计算-setter
- kNN算法——菜鸟学习机器学习实战
- glfw开发步骤
- docker 端口编
- Spark Rpc的启动过程(其实也就是集群的启动过程)
- C++实现计数排序
- 进程间通信之--- 管道
- webservice 前端gsoap 使用总结
- Groovy的入门
- windows server 2008 r2服务器出现蓝屏
- TCP为啥要三次握手,四次挥手?
- Win10下Java开发环境配置
- spring配置静态资源访问的3种方式
- 再谈tcp流式传输和udp数据报传输------大家顺便来做做这两个题目!