java排序之【基数排序】

使用低位到高位的顺序,基数为10,使用单向链表接收每一次排后的值,再倒回数组,来回n次(n为最大数值位数)后即排好。写的程序貌似运行很慢,自己也不满意,请大家指点一下~

感觉不如直接用数组倒腾,书上说用10个链表实现,但是不懂怎么做以及为什么要这样做,如何提高效率呢?


package LianXi;

import java.util.Arrays;
import java.util.Random;

//负数对10取余也是负数
class Link5 {
    Link5 next;
    int data;

    public Link5(int i) {
        data = i;
    }
}

public class BaseNumSort {
    static Link5 f;
    static int[] a;
    static int n;// 最大位数

    static void sort() {
        int count = 0;
        while (count < n) {
            count++;
            for (int i = 0; i < 10; i++) {// 0~9
                for (int j = 0; j < a.length; j++) {
                    if (count == 1) {
                        if (a[j] % 10 == i)// 根据个位排列
                            insert(a[j]);
                    } else if (count == 2) {
                        if (a[j] / 10 % 10 == i)// 十位
                            insert(a[j]);
                    } else {//其他位
                        int temp = (int) Math.pow(10, count - 1);
                        if (a[j] / temp == i)
                            insert(a[j]);
                    }
                }
            }
            for (int k = a.length - 1; k >= 0; k--) {
                a[k] = remove();
            }
        }
    }

    static void insert(int j) {
        Link5 newlink = new Link5(j);
        if (isEmpty()) {
            f = newlink;
        } else {
            newlink.next = f;
            f = newlink;
        }
    }

    static boolean isEmpty() {
        return (f == null);
    }

    static int remove() {
        int temp = f.data;
        f = f.next;
        return temp;
    }

    public static void main(String[] args) {
        n = 2;
        int size = 20;
        a = new int[size];
        Random rand = new Random();
        System.out.println("排序前:");
        for (int i = 0; i < size; i++) {
            int n = rand.nextInt(size * 5);
            System.out.print(n + " ");
            a[i] = n;
        }
        System.out.println("\n排序后:");
        sort();
        System.out.println(Arrays.toString(a));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值