数据结构和算法——八种常用的排序算法------基数排序

基数排序

   基数排序就是先按照低位排序,然后收集排序后的结果,然后在按照高位排序,再收集排序结果,以此类推,直到最高位。

排序的过程演示:
在这里插入图片描述
代码演示:


import java.util.Arrays;

public class RadixSort {
    public static void main(String[] args) {
        int[] arr = new int[]{1,3,69,45,23,76,67,789,645,32};
        radixSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    private static void radixSort(int[] arr) {
        //先把数组中的最大数找出来看一共要比较几次
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max){
                max = arr[i];
            }
        }
        //比较的次数
        String s = max+"";
        int maxlength = s.length();
        //存储临时数据的二维数组
        int[][] temp = new int[10][arr.length];
        //记录在temp中相应的数组中存放的元素的数量
        int[] counts = new int[arr.length];
        for (int i = 0,n = 1; i < maxlength; i++,n *= 10) {
            //取出每一个元素
            for (int j = 0; j < arr.length; j++) {
                //计算每个元素的余数
                 int ys = arr[j]/n%10;
                 //把当前遍历的元素放入临时数组中
                 temp[ys][counts[ys]] = arr[j];
                 //记录里面的数组的下标
                 counts[ys]++;
            }
            int index = 0;
            //把临时数组的元素取出来,放进原数组中
            for (int k = 0; k < counts.length; k++) {
                if (counts[k] != 0){
                    for (int l = 0; l < counts[k]; l++){
                        arr[index] = temp[k][l];
                        index++;
                    }
                    counts[k] = 0;
                }
            }
        }
    }
}

执行结果:
在这里插入图片描述

发布了58 篇原创文章 · 获赞 7 · 访问量 2300

猜你喜欢

转载自blog.csdn.net/weixin_42492089/article/details/102965018