计数排序-基数排序
来源:互联网 发布:mac 远程 编辑:程序博客网 时间:2024/05/17 23:18
http://www.wutianqi.com/?p=2378
一.计数排序(Counting Sort)
基本思想:对每一个输入元素x,确定出小于x的元素个数。
适用范围:适用于输入是由小范围的整数构成的序列。
稳定性:算法是稳定的。
具体实现:
#include <iostream>using namespace std; // arr--初始输入数组, res--存放排序结果的数组,hash临时存储区[0...k]int arr[100], res[100], hash[100];int len, k = -1; void PrintHash(){cout << "Hash数组: " << endl;for(int i=0; i<=k; ++i)cout << hash[i] << " ";cout << endl;} void countingSort(){for(int i=0; i<=k; ++i)hash[i] = 0;// 此过程记录每一个元素的个数for(int i=1; i<=len; ++i)++hash[arr[i]];PrintHash();// 此过程确定小于x的元素的个数for(int i=1; i<=k; ++i)hash[i] += hash[i-1];PrintHash();// 思考这里为何从i=len开始?而不从i=1开始?for(int i=len; i>0; --i){res[hash[arr[i]]] = arr[i];--hash[arr[i]];}}/*思考这里为何从i=len开始?而不从i=1开始?保持排序后结果的稳定性!因为同一个元素,靠后的元素在排序后相对也是从后开始存入结果数组的。*/ int main(){cout << "输入元素个数: ";cin >> len;cout << "输入" << len << "个元素: " << endl;for(int i=1; i<=len; ++i){cin >> arr[i];if(k < arr[i])k = arr[i];}countingSort();cout << "排序后结果为: " << endl;for(int i=1; i<=len; ++i)cout << res[i] << " ";cout << endl;}
输出结果:
二.基数排序(Radix Sort)
基本思想:按组成关键字的各个位的值来实现排序的。
排序方式:
排序方式:LSD 由右向左排; MSD 由左向右排
稳定性:算法是稳定的。
推荐:严蔚敏《数据结构》上的基数排序。
先说下什么是基数:计算的基数就是基本的单元数。比如10进制的基数就是10,二进制的基数就2,八进制的基数是8等等。
基数排序说通俗点,就是把带排序的N个数字右对齐排成一列。然后把相同的位数互相比较,来排序。
例图:
以下是具体实现和分析:
#include <iostream>#include <cstring>using namespace std; int arr[100], res[100], hash[10];int n; int maxbit(){ int _max = 0; int temp[100]; for(int i=0; i<n; ++i) temp[i] = arr[i]; for (int i=0; i<n; ++i) { int tt = 1; while(temp[i]/10 > 0) { tt++; temp[i] /= 10; } if(_max < tt) _max = tt; } cout << "_max : " << _max << endl; return _max;} void radixSort(){memset(res, 0, sizeof(res));int nbit = maxbit();int tmp;int radix = 1;// 以下和计数排序一样for(int i=1; i<=nbit; ++i){for(int j=0; j<10; ++j)hash[j] = 0;for(int j=0; j<n; ++j){tmp = (arr[j]/radix)%10;++hash[tmp];}for(int j=1; j<10; ++j)hash[j] += hash[j-1];for(int j=n-1; j>=0; --j){tmp = (arr[j]/radix)%10;--hash[tmp];res[hash[tmp]] = arr[j];}for(int j=0; j<n; ++j)arr[j] = res[j];radix *= 10;}} int main(){freopen("input.txt", "r", stdin);cout << "输入元素个数: ";cin >> n;cout << "输入" << n << "个元素: " << endl;for(int i=0; i<n; ++i)cin >> arr[i];radixSort();cout << "排序后结果为: " << endl;for(int i=0; i<n; ++i)cout << res[i] << " ";cout << endl;}
- 计数排序,基数排序
- 计数排序和基数排序
- 计数排序-基数排序
- 计数排序和基数排序
- 基数排序和计数排序
- 计数排序和基数排序
- 计数排序+基数排序
- 计数排序和基数排序
- 基数排序/计数排序
- 计数排序和基数排序
- 基数排序,计数排序
- 计数排序和基数排序
- 计数排序实现基数排序
- 基数排序与计数排序
- 【java】计数排序 基数排序
- 计数排序和基数排序
- 计数排序和基数排序
- 计数排序和基数排序
- Hdu 1232 畅通工程
- yy笔试回忆
- You cannot combine custom titles with other title feature..
- 什麼是taxonomy, taxonomy access
- flashbuilder4 单选 RadioButton RadioButtonGroup
- 计数排序-基数排序
- C++程序设计体验
- 面向对象设计原则汇总
- Hdu 1213 How Many Tables
- WM_COMMAND 和 WM_NOTIFY 的区别
- myibatis学习笔记
- Android layout xml属性总结
- 面向对象设计原则理解
- Android conversion to dalvik format failed with error 1的解决办法