Good Java programmer learning routes Share 5 minutes to understand Radix Sort

  Good Java programmer learning routes Share 5 minutes to understand radix sort, foreword: radix sort without having to compare and exchange, but to use the distribution and collection operations to achieve two basic sort. Radix sort is divided into two: the first is LSD, ordered from lowest-order bit; the second is MSD, ordered from most significant bit.

Radix sort idea introduced

Assignment: the digital, each bit in the range 0-9, the container 10 is required (which may be referred we barrel), reference numeral which is 10 barrels 0-9. Every trip sorting, we take each element in the bit value sequentially into the bucket.

  1. Collection: After a trip to the sort is complete, we order from 0-9 buckets order to take elements.

  2. Distribution and collection continues until the maximum number of the sort is complete.

Algorithm description:

Sort the data to be: 12, 34, 2, 123, 25, 59, 37

The use of LSD, from a low start sorting

The first round: take a number of bits, into a corresponding barrel, such that digit 2 of 12, into barrel number 2; 4 digits is 34, into the tub 4

Good Java programmer learning routes Share 5 minutes to understand Radix Sort

After the first round, the data obtained: 12, 2, 123, 34, 25, 37, 59

Second round: take ten digits, into the bucket. 2 For example, ten digits is 0, No. 0 into the barrel

Good Java programmer learning routes Share 5 minutes to understand Radix Sort

After the second round, the data obtained: 2, 12, 123, 25, 34, 37, 59

Third round: take hundreds digit, into the bucket

Good Java programmer learning routes Share 5 minutes to understand Radix Sort

Finally, the data orderly 2, 12, 25, 34, 37, 59, 123

Radix sort of code implementation

private static void radixSort(int[] arr) {
//存储最大值,暂时记录为第一个元素
int max = arr[0];
//获取待排序数组中的最大值
for (int v : arr) {
if (v > max) {
max = v;
}
}
// 用列表表示桶,一共10个桶,每个桶对应的元素也是列表
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i = 0; i < 10; i ++) {
list.add(new ArrayList<Integer>());
}
// 确定循环轮数
for(int i = 0, factor = 1; i < max; factor *= 10, i ++) {
for(int j = 0; j < arr.length; j ++) {
// 根据相应的位(个位/十位...)取通号,然后将数据放入桶中
list.get((arr[j] / factor) % 10).add(arr[j]);
}
// 遍历桶,将其中数据放入arr数组中
for(int j = 0, k = 0; j < list.size(); j ++) {
while(!list.get(j).isEmpty()) {
arr[k] = list.get(j).get(0);
list.get(j).remove(0);
k++;
}
}
}
}

to sum up

Radix sort is a method by recording the value of keywords you sort of step by step. Keyword is generally applicable to the recording of an integer type, for sorting character strings and is not suitable.

Guess you like

Origin blog.51cto.com/14479068/2427464