【Java数据结构】了解排序相关算法

基数排序

基数排序是桶排序的扩展,本质是将整数按位切割成不同的数字,然后按每个位数分别比较最后比一位较下来的顺序就是所有数的大小顺序。

  • 先对数组中每个数的个位比大小排序
  • 然后按照队列先进先出的顺序分别拿出数据
  • 再将拿出的数据分别对十位百位千位等位数比较大小,直到数组中最大值排完位数就结束(如果数组中位数不一致时,就相当于在高位添加0)
  • 最后一位排序完的结果就是最终排序的顺序。

关于基数排序大家可以了解原理即可,下面采用的是二维数组实现基数排序:

复制代码
    public static void main(String[] args) {
        int[] arr = { 4, 3, 7, 4, 9, 2, 10,171 };
        sort(arr);
        System.out.println(Arrays.toString(arr));

    }
    public static void sort(int[] arr) {
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        int maxLength = 0;
        int ret = max;
        while (ret != 0){
            ret /= 10;
            maxLength++;
        }

        int[][] cur = new int[10][arr.length-1];
        int[] elementCount = new int[10];

        int n = 1;
        for(int i=0; i<maxLength; i++) {
            //基数排序的核心是下面两个for循环
            for (int j = 0; j < arr.length; j++) {
                int len = arr[j]/n % 10;
                cur[len][elementCount[len]] = arr[j];
                elementCount[len]++;
            }
            int index = 0;
            for (int j = 0; j < elementCount.length; j++) {
                if (elementCount[j] != 0) {
                    for (int t = 0; t < elementCount[j]; t++) {
                        arr[index] = cur[j][t];
                        index++;
                    }
                }
                elementCount[j] = 0;
            }
            n=n*10;
        }
    }

计数排序

计数数组是通过计数进行存数据,最后打印数据。

  • 首先我们需要找出数组中最大最小值

  • 然后再创建一个最大值减最小值的差值个计数数组

  • 然后分别遍历原数组中每一个数值,每遍历一个计数数组相应位置加1,直至数组遍历完

  • 最后再将计数数组中的数一个一个赋值给原数组中,这样就结束了

    public static void countSort(int[] arr){
    int min = arr[0];
    int max = arr[0];
    for (int i = 1; i < arr.length; i++){
    if (min > arr[i]){
    min = arr[i];
    }
    if (max < arr[i]){
    max = arr[i];
    }
    }
    int[] count = new int[max - min+1];
    for (int i = 0; i < arr.length; i++){
    count[arr[i] - min]++;
    }
    int n = 0;
    for (int i = 0; i < count.length; i++){
    while (count[i] != 0){
    arr[n] = i+min;
    n++;
    count[i]--;
    }
    }
    }
    public static void main(String[] args) {
    int[] arr = { 4, 3, 7, 4, 9, 2, 10,171 };
    countSort(arr);
    System.out.println(Arrays.toString(arr));

    }

当面临数组中比较稀疏的数值是,这个计数排序就会浪费很多空间,所以一般也不常使用这个排序,了解一下即可。

相关推荐
Run_Teenage39 分钟前
手撕——贪吃蛇小游戏(下)
c语言·数据结构·链表
PXM的算法星球2 小时前
【leetcode】3524 求出数组的X值1
算法·leetcode·职场和发展
椰羊~王小美4 小时前
LeetCode -- Flora -- edit 2025-04-27
算法·leetcode·职场和发展
缘友一世5 小时前
从线性回归到逻辑回归
算法·逻辑回归·线性回归
前端_学习之路6 小时前
javaScript--数据结构和算法
javascript·数据结构·算法
weixin_428498496 小时前
使用HYPRE库并行装配IJ稀疏矩阵指南: 矩阵预分配和重复利用
算法·矩阵
雾削木8 小时前
mAh 与 Wh:电量单位的深度解析
开发语言·c++·单片机·嵌入式硬件·算法·电脑
__lost8 小时前
小球在摆线上下落的物理过程MATLAB代码
开发语言·算法·matlab
8RTHT9 小时前
数据结构(七)---链式栈
数据结构
mit6.82410 小时前
[Lc_week] 447 | 155 | Q1 | hash | pair {}调用
算法·leetcode·哈希算法·散列表