zoukankan      html  css  js  c++  java
  • Java CountingSort

    Java CountingSort

    /**
     * <html>
     * <body>
     *  <P> Copyright 1994-2018 JasonInternational </p>
     *  <p> All rights reserved.</p>
     *  <p> Created on 2018年4月10日 </p>
     *  <p> Created by Jason</p>
     *  </body>
     * </html>
     */
    package cn.ucaner.algorithm.sorts;
    
    /**
     * Counting sort is an algorithm for sorting a collection of objects according
     * to keys that are small integers; that is, it is an integer sorting algorithm.
     * It operates by counting the number of objects that have each distinct key
     * value, and using arithmetic on those counts to determine the positions of
     * each key value in the output sequence. 
     * <p>
     * Family: Counting.<br>
     * Space: An Array of length r.<br> 
     * Stable: True.<br>
     * <p>
     * Average case = O(n+r)<br>
     * Worst case = O(n+r)<br>
     * Best case = O(n+r)<br>
     * <p> 
     * NOTE: r is the range of numbers (0 to r) to be sorted.
     * <p>
     * @see <a href="https://en.wikipedia.org/wiki/Counting_sort">Counting Sort (Wikipedia)</a>
     * <br>
     * @author Justin Wetherell <phishman3579@gmail.com>
     */
    public class CountingSort {
    
        private CountingSort() { }
    
        public static Integer[] sort(Integer[] unsorted) {
            int maxValue = findMax(unsorted);
            int[] counts = new int[maxValue + 1];
            updateCounts(unsorted, counts);
            populateCounts(unsorted, counts);
            return unsorted;
        }
    
        private static int findMax(Integer[] unsorted) {
            int max = Integer.MIN_VALUE;
            for (int i : unsorted) {
                if (i > max)
                    max = i;
            }
            return max;
        }
    
        private static void updateCounts(Integer[] unsorted, int[] counts) {
            for (int e : unsorted)
                counts[e]++;
        }
    
        private static void populateCounts(Integer[] unsorted, int[] counts) {
            int index = 0;
            for (int i = 0; i < counts.length; i++) {
                int e = counts[i];
                while (e > 0) {
                    unsorted[index++] = i;
                    e--;
                }
            }
        }
    }
    

      

  • 相关阅读:
    设计模式之组合模式
    设计模式之桥接模式
    设计模式之装饰模式
    设计模式之代理模式
    总结的一些MySQL索引相关的知识点
    软件架构设计-五视图方法论
    博客迁移
    IMDB.COM排名算法(贝叶斯公式)和Reddit评论排行算法
    利用ratchet 和 ZeroMQ 实现即时(推送)聊天的功能
    composer Ratchet 实验心得
  • 原文地址:https://www.cnblogs.com/jasonandy/p/9243205.html
Copyright © 2011-2022 走看看