简介
基数排序(英语:Radix sort)是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。由于整数也可以表达字符串(比如名字或日期)和特定格式的浮点数,所以基数排序也不是只能使用于整数。基数排序的发明可以追溯到1887年赫尔曼·何乐礼在打孔卡片制表机(Tabulation Machine)上的贡献[1]。
它是这样实现的:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。
基数排序的方式可以采用LSD(Least significant digital)或MSD(Most significant digital),LSD的排序方式由键值的最右边开始,而MSD则相反,由键值的最左边开始。
java代码实现
package com.gcp.www;
import java.util.ArrayList;
import java.util.List;
public class RadixSort {
public int[] radixSort(int[] A,int n) {
// write code here
//计算大于等于0的个数
int posCount = 0;
for(int i = 0 ; i < n;i++){
if(A[i] >= 0 ){
posCount++;
}
}
int[] posArray = new int[posCount]; //正数数组
int[] negArray = new int[n - posCount]; //负数数组
int posIndex = 0;
int negIndex = 0;
for(int i = 0 ; i < n;i++){
if(A[i] >= 0 ){
posArray[posIndex++] = A[i];
}else{
negArray[negIndex++] = A[i];
}
}
for(int i = 0 ; i < negArray.length;i++){ //将负数全部转换为正数
negArray[i] = -negArray[i];
}
posArray = radixSort(posArray);
negArray = radixSort(negArray);
//从小到大赋值到A数组
int index = 0;
for( int i = negArray.length - 1;i >=0 ;i--){
A[index++] = -negArray[i];
}
for(int i = 0 ; i < posArray.length;i++){
A[index++] = posArray[i];
}
return A;
}
public int[] radixSort(int[] A) {
// write code here
if(A == null || A.length < 2){
return A;
}
int max = A[0];
for(int i = 0;i < A.length;i++){ //找到排序的最大值
max = Math.max(max, A[i]);
}
List<List<Integer>> lists = new ArrayList<List<Integer>>();
for(int i = 0 ; i < 10;i++){ //准备10个桶
lists.add(new ArrayList<>());
}
int[] array = new int[A.length];
for(int i = 0 ; i < A.length;i++){
array[i] = A[i];
}
//获取最大值的位数
int intCount = getIntCount(max);
for(int i = 0; i < intCount ;i++){ //排序次数
int index = 0;
int arrayIndex = 0;
for(int j = 0 ; j < array.length;j++){
index = getIntByIndex(array[j],i);
lists.get(index).add(array[j]); //放入对应的桶中
}
index = 0;
for (List<Integer> list : lists) {
for (Integer integer : list) {
array[index++] = integer;
}
lists.get(arrayIndex++).clear();
}
}
return array;
}
public int getIntByIndex(int n,int index){ //通过索引获取第几位的数字
int count = getIntCount(n);
if(index+1 > count){
return 0;
}
int result = 0 ;
while((index+1) > 0){
result = n % 10;
n = n/10;
index--;
}
return result;
}
public int getIntCount(int n){
int count = 0;
if(n == 0){
return 1;
}
while(n > 0){
count++;
n = n/10;
}
return count;
}
public static void main(String[] args) {
int[] A = {54,35,48,36,27,12,44,44,8,14,26,17,28,-1,-3};
A = new RadixSort().radixSort(A, A.length);
for (int i : A) {
System.out.println(i);
}
}
}