(1.3.6.1)线性排序:基数排序
来源:互联网 发布:算法统宗圆中正方形 编辑:程序博客网 时间:2024/06/14 12:59
前言
当序列中元素范围比较大时,就不适合使用计数排序。针对这种情况,就有了基数排序(Radix Sort),这是一种按位排序。它仍然是以计数排序为基础。
基数排序
基数排序的基数:十进制数的基数自然是10,二进制的基数自然是2。通常有两种按位排序策略:1.高位优先法(most significant digit first,MSD):简单讲就是从高位排起。2.低位优先法(least significant digit first,LSD):它与高位优先相反,从低位排起。从排序效果上看,高位优先比较直观,但却涉及到递归的过程,故最常用的还是低位优先法。说它以计数排序为基础,理由如下,以最常见的十进制数为例:
仔细理解上图,高位优先的过程你也一定可以推测出来。下面给出低位优先下的代码。
代码
- #include<iostream>
- #include<iomanip>
- using namespace std;
- //获取最大位数
- int get_max_digit(int array[], int n)
- {
- int digit, max;
- digit = 0;
- max = array[0];
- for (int i = 1; i < n; i++)
- {
- if (array[i] > max)
- max = array[i];
- }
- while (max)
- {
- digit++;
- max /= 10;
- }
- return digit;
- }
- //基数排序
- void RadixSort(int array[], int n)
- {
- //创建临时数组
- int *temp = new int[n];
- //位数:决定了排序趟数
- int digit = get_max_digit(array, n);
- //计数数组
- int count[10];
- //排序
- int r, i, d;
- for (r = 1; r <= digit; r++)
- {
- //重置计数数组
- memset(count, 0, 10 * sizeof(int));
- //把数据存储到临时数组
- memcpy(temp, array, n*sizeof(int));
- d = i = 1;
- while (i < r)
- {
- i++;
- d *= 10;
- }
- for (i = 0; i < n; i++)
- count[(array[i] / d) % 10]++;
- for (i = 1; i < 10; i++)
- count[i] += count[i - 1];
- //数据回放
- for (i = n - 1; i >= 0; i--)
- array[--count[(temp[i] / d) % 10]] = temp[i];
- }
- }
- void print(int array[], int n)
- {
- for (int i = 0; i < n; i++)
- cout << setw(6) << array[i];
- cout << endl;
- }
- int main()
- {
- cout << "******基数排序***by David***" << endl;
- int array[] = { 123, 234, 45, 111, 6, 128 };
- int n = sizeof(array) / sizeof(int);
- cout << "原序列" << endl;
- print(array, n);
- cout << "基数排序" << endl;
- RadixSort(array, n);
- print(array, n);
- system("pause");
- return 0;
- }
运行
0 0
- (1.3.6.1)线性排序:基数排序
- 线性排序之基数排序
- 线性排序之:基数排序
- 【算法导论】第五课 线性排序(基数排序 计数排序)
- 线性时间排序之基数排序
- 线性排序----计数排序, 基数排序, 桶排序
- 线性排序算法(计数排序,基数排序,桶排序)分析及实现
- 数据结构与算法——线性时间排序(计数排序、基数排序、桶排序)
- 算法导论 第8章 线性时间排序(计数排序、基数排序、桶排序)
- 三大线性排序之基数排序
- 线性时间排序之——基数排序
- 整数的线性排序算法-基数排序
- 五 线性时间排序(基数排序、计数排序和桶排序)
- 线性时间排序——计数排序,基数排序,桶排序
- 算法导论-- 线性时间排序(计数排序、基数排序、桶排序)
- 线性排序之基数排序,桶排序,计数排序
- 线性时间排序之计数排序,基数排序和桶排序
- 线性时间排序(计数排序/桶排序/基数排序)
- 【LeetCode】 Populating Next Right Pointers in Each Node 完全二叉树
- Search Insert Position
- c8051f 分页机制,调试时看到的可能不是真实值
- Ubuntu Windows双系统更改启动项顺序
- CVTE公司面经
- (1.3.6.1)线性排序:基数排序
- php中explode与split的区别
- 巧用Squid的ACL和访问列表实现高效访问控制(51CTO)
- struct和typedef struct
- Java单例程个人思考
- C 01
- MySQL group by 单字分组序和多字段分组
- 2015年创业中遇到的技术问题:21-30
- URAL 1823 — Ideal Gas