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);
}
}
计数排序
最新推荐文章于 2024-11-16 14:38:00 发布