计数排序
来源:互联网 发布:第三方辅助软件 编辑:程序博客网 时间:2024/06/06 06:31
package com.algorithm.sort;/** * Created by yamorn on 15-3-29. *//* 计数排序:对于每一个输入元素x,确定小于x的元素个数。利用这一信息,直接把x放到它在输出数组中的位置上。 例如,如果由17个元素小于x,则x就应该放在第18个位置上。 计数排序时稳定的:具有相同值的元素在输出数组中的相对位置次序在它们的输出数组中的相对次序相同. */public class CountingSort { // elements in array a less than number k public static int[] countingSort(int[] a, int k) { int[] c = new int[k]; int[] b=new int[a.length]; for (int i = 0; i < k; i++) c[i] = 0; for(int j=0;j<a.length;j++) c[a[j]]=c[a[j]]+1; //c[i] now contains the number of elements equal to i for(int i=1;i<k;i++) c[i]=c[i]+c[i-1]; //c[i] now contains the number of elements less than or equal to i for (int j = a.length - 1; j >=0; j--) { b[c[a[j]]-1] = a[j]; c[a[j]]=c[a[j]]-1; } return b; } private static void print(int[] data) { for (int i : data) { System.out.print(i + " "); } System.out.println(); } public static void main(String[] args) {// int[] a=new int[]{2,5,3,0,2,3,0,3}; int[] a = new int[]{6, 0, 2, 0, 1, 3, 4, 6, 1, 3, 2}; int[] out = countingSort(a, 7); print(out); }}
0 0
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 计数排序
- 如何优化MySQL insert性能
- Jackrabbit 学习笔记 1 入门
- Android将程序崩溃信息保存本地文件
- 数据库原理第二章作业
- p51,8
- 计数排序
- 一些常用字符串操作函数的内部实现
- 用CSS实现水平方向菜单&竖直方向菜单&下拉菜单
- 《程序的编译,链接,运行》读书笔记
- Java 中按值传递和引用传递的区别
- 转载自廖雪峰的网站,只是为了便于保存,---gita安装
- 初识OC 面向对象OPP(MS)
- 用 FileChannel 拷贝文件
- 编程范式随课笔记(二)