基数排序

来源:互联网 发布:现货交易平台软件 编辑:程序博客网 时间:2024/06/04 18:12

package com.itheima;

import java.util.ArrayList;
import java.util.List;

/**
* 基数排序:从最低为开始依次比较,然后到高位。
* @author qingchao
*
*/
public class RadixSort {

/** * 基数排序的方法 */public static void radixSort(){    int a[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51};       sort(a);    for (int i = 0; i < a.length; i++) {        System.out.println(a[i]);    }}/** * 排序的主要算法实现 */public static void sort(int[] array){    //首先确定排序的次数    //用过打擂台算法求出待排序数中最大值    int max = array[0];    for (int i = 1; i < array.length; i++) {        if (array[i] > max) {            max = array[i];        }    }    int time = 0;    //判断最大数的位数(决定了比较多少次)    while (max > 0) {        max /= 10;        time ++;    }    //建立10个队列(每位数字的范围0 ~ 9)    List<ArrayList> queue = new ArrayList<ArrayList>();    for (int i = 0; i < 10; i++) {        ArrayList<Integer> queue1 = new ArrayList<Integer>();        queue.add(queue1);    }    //进行time次分配和收集    for (int i = 0; i < time; i++) {        //分配数组元素        for (int j = 0; j < array.length; j++) {            //得到数字的第 time + 1 位数            int x = array[j] % (int)Math.pow(10,i+1)/(int)Math.pow(10, i);             ArrayList<Integer> queue2 = queue.get(x);            queue2.add(array[j]);            queue.set(x, queue2);        }        int count = 0;//元素计数器        //收集队列元素        for (int k = 0; k < 10; k++) {            while (queue.get(k).size() > 0) {                ArrayList<Integer> queue3 = queue.get(k);                array[count] = queue3.get(0);                queue3.remove(0);                count ++;            }        }    }}public static void main(String[] args) {    // TODO Auto-generated method stub     radixSort();}

}
运行结果:
4
5
12
13
15
17
18
23
25
27
34
34
35
38
49
49
51
53
54
56
62
64
65
76
78
97
98
99
101

0 0