zoukankan      html  css  js  c++  java
  • 计数排序

    计数排序

      思路: 

        负数暂不考虑,后续维护

        1- 找出数组中的最大值,新建一个  最大值+1  长度大小的数组

        2- 数组中的数据 作为计数数组的下标,值存出现的次数

             3- 循环计数数组,value > 0 将下标放入结果数组

      时间复杂度:   O(n + k)

      空间复杂度:O(k)


     (一)代码

    public class CountingSort {
    
        public static void main(String[] args) {
    
            int arr[] = new int[]{3,3,4,7,13,435,54,2,6666,234};
            countingSort(arr);
            System.out.print(Arrays.toString(arr));
    
        }
    
        private static void countingSort(int[] arr) {
    
            //获取数组最大值
            int maxval = getMaxValue(arr);
    
            //新建计数 数组  大小为max + 1 考虑0
            int[] count = new int[maxval+1];
            for(int value : arr){
                count[value]++;
            }
    
            int countingIndex = 0;
            for(int i = 0 ; i < count.length ; i++) {
                while (count[i] > 0) {
                    arr[countingIndex++] = i;
                    count[i]--;
                }
            }
        }
    
        private static int getMaxValue(int[] arr) {
    
            int max = 0;
            for(int ar : arr){
                if(ar > max){
                    max = ar;
                }
            }
    
            return max;
        }
    }


     

              迎着光的方向

     

  • 相关阅读:
    四则运算实现
    第四周例行报告
    代码规范,结对要求
    第三周例行报告
    第三周作业3功能测试
    第二周例行报告
    第一次作业汇总
    2017/2/24:Maven的pom jar war的区别
    oracle的常用99条语句
    2017/2/21:配置自己的中文乱码拦截器
  • 原文地址:https://www.cnblogs.com/misscai/p/14958906.html
Copyright © 2011-2022 走看看