java 计数排序


java 计数排序

 

 

**************************

计数排序

 

        

算法描述:找出数组的最大值max、最小值min,创建数组count(长度为max-min+1)

遍历原数组元素,数值减去min,可得count中的索引位index,索引位的数值加1;

遍历count数组,索引位+min可得原数值,count数组index为的数值为数据出现个数,将数据还原到原数组中,排序完成

说明:基数排序适用于整数,且max-min相差不大的场景

 

空间复杂度:计数排序需要使用max-min+1的额外空间

时间复杂度:o(n)

算法稳定性:计数排序是稳定的排序算法

 

 

**************************

示例

 

public class MyTest9 {

    public static int[] generate(int length){
        int[] a=new int[length];

        Random random=new Random();
        for (int i=0;i<length;i++){
            a[i]=random.nextInt(1000);
        }

        return a;
    }

    public static void countSort(int[] a){
        int min=a[0],max=a[0];

        for (int value : a) {
            if (min > value) {
                min = value;
            }

            if (max < value) {
                max = value;
            }
        }

        if (min==max){
            return;
        }

        int[] count=new int[max-min+1];
        for (int value : a){
            count[value-min]++;
        }

        int index=0;
        for (int i=0;i<count.length;i++){
            if (count[i]!=0){
                while (count[i]-- > 0){
                    a[index++]=i+min;
                }
            }
        }
    }

    public static void main(String[] args){
        int[] a=generate(10);
        System.out.println("数组排序前为:");
        Arrays.stream(a).forEach(i -> System.out.print(i+" "));

        countSort(a);
        System.out.println("\n\n数组排序后为:");
        Arrays.stream(a).forEach(i -> System.out.print(i+" "));
    }
}

 

控制台输出

数组排序前为:
607 485 993 643 952 695 851 655 822 195 

数组排序后为:
195 485 607 643 655 695 822 851 952 993 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值