asdfas
package com.zhoujie;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class RadixSort {
public static final int ARRAY_LENGTH = 10;
public static final int ARRAY_MAX_VALUE = https://www.it610.com/article/1000;
public static final String LOG_PREFIX ="=====================";
public static final String LOG_SUFFIX = LOG_PREFIX;
public static final String ARR_DELIMITER = "\t";
public static void main(String[] args) {
// 1. generate input array
Random random = new Random();
int[] intArr = new int[ARRAY_LENGTH];
printLine(LOG_PREFIX + "The original array is:" + LOG_SUFFIX);
for (int i = 0;
i < intArr.length;
i++) {
intArr[i] = random.nextInt(ARRAY_MAX_VALUE);
print(intArr[i]);
if (i != intArr.length - 1) {
print(ARR_DELIMITER);
}
}
printLine("");
// 2. radix sort
radixSort(intArr);
// 3. print sorted array
printLine(LOG_PREFIX + "The sorted array is:" + LOG_SUFFIX);
printLine(join(intArr, ARR_DELIMITER));
} private static void radixSort(int[] intArr) {
int maxDigits = String.valueOf(ARRAY_MAX_VALUE).length();
for(int i = 1;
i <= maxDigits;
i ++){
sortByDigit(intArr, i);
}
} private static void sortByDigit(int[] intArr, int i) {
Map> map = new TreeMap>();
for(int item : intArr){
int digit = getDigit(item, i);
List list = map.get(digit);
if(list == null){
list = new ArrayList();
map.put(digit, (ArrayList) list);
}
list.add(item);
}
int index = 0;
for(int key : map.keySet()){
List list = map.get(key);
for(int item : list){
intArr[index++] = item;
}
}
} private static int getDigit(int item, int i) {
StringBuilder sb = new StringBuilder(String.valueOf(item));
String reverseStr = sb.reverse().toString();
if(reverseStr.length() >= i){
return Integer.valueOf(reverseStr.charAt(i-1));
} else {
return 0;
}
} public static void print(Object t) {
System.out.print(t);
} public static void printLine(Object t) {
System.out.println(t);
} public static String join(int[] arr, String delimiter) {
StringBuilder sb = new StringBuilder();
for (int element : arr) {
sb.append(element);
sb.append(delimiter);
}
return sb.substring(0, sb.length());
}}
【【算法导论】第八章之基数排序】alsdlfs
推荐阅读
- Python - Search Insert Position
- Leetcode35 搜索插入位置
- Data|单链表的增删查改
- 软件编程|STL使用总结
- Probabilistic|一次遍历等概率选取字符串中的某个字符
- 欧几里得算法(即辗转相除法)的时间复杂度log(N)的简洁证明
- 八皇后问题 回溯递归 C语言版
- memcopy
- HMM与序列标注
- 计算复杂性理论