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--;
}
}
}
}

  

最新文章

  1. 【转】C# 中 10 个你真的应该学习(和使用!)的功能
  2. java 遍历arrayList的四种方法
  3. jQuery 名称冲突
  4. python-program
  5. Android系统目录介绍
  6. 用css 制作三角
  7. gravity、layout_gravity及orientation
  8. 在CentOS6.7操作系统上编译安装httpd2.4
  9. 创建laravel项目时打开浏览器常见错误
  10. MemcacheQ 的安装与使用
  11. JAVA中的策略模式
  12. The sound of silence引发的关于互联网以及教育的利弊思考
  13. java7增强的try语句关闭资源
  14. “战术竞技类”外挂打击已开始!揭秘腾讯We Test游戏安全服务新动作!
  15. Windows--常见端口号
  16. Javascript URI 解析介绍
  17. S2算法应用
  18. libgdx学习记录20——多线程MultiThread资源处理
  19. Educational Codeforces Round 14 C. Exponential notation 数字转科学计数法
  20. Zabbix之Python脚本端口自动发现

热门文章

  1. Cesium获取经度 ,纬度,高度
  2. OpenJudge计算概论-取石子游戏
  3. React拾遗(下)
  4. 123457123457#0#-----com.cym.shuXueWangGuo1--前拼后广--儿童数学
  5. Oracle ORA-00984: column not allowed here
  6. .NET CORE添加引用包
  7. LD_LIBRARY_PATH无效
  8. html设置多个div并排显示
  9. 转载【oracle切换表空间】
  10. iOS算法题