排序算法大全之计数排序

来源:互联网 发布:国家对于网络审查 编辑:程序博客网 时间:2024/05/22 03:33

计数排序是一个比较简单的排序算法

计数排序基本思想:

计数排序首先有一个大的前提,假设n个输入元素中每一个介于0到k之间的整数,此处k为某个整数   (还有计数排序是一种稳定的排序)

1.就是对每一个输入元素x,确定小于x元素的个数。例如,如果有17个元素小于x,则将x插入在第18位。

2.当有几个相同元素时,这个方案要略做修改,因为不能把它们放在同一个输出位置上。

计数排序不是就地排序,也不是比较排序,所以他的时间复杂度可以小于nlogn;

伪代码:

couting_sort(A,B,k)

for i = 0 to k

do  C[i] = 0

for i = 1 to length[A]

do C[A[j]] = C[A[j]] +1;

for i = 1 to k

do C[i] = C[i] + C[i-1];

for j = length[A] downto 1

do B[C[A[j]]] = a[j]

     C[A[j]] = C[A[j]]-1



用java代码表示:

/** * @author WuKung * @csdnURL http://blog.csdn.net/wu_kung/ * @createdDate 2014-4-18 上午9:59:39 */public class CoutingSortTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[] a = {3,2,4,6,4,2,4,5,3};int[] b = couting_sort(a, 6);for(int i=0;i<b.length;i++){System.out.print(b[i]+" ");}}public static int[] couting_sort(int[] a,int k){if(a==null||k<0){return null;} int[] b = new int[a.length]; int[] c = new int[k+1]; //统计a中的每个数的个数 for(int i=0;i<a.length;i++){ c[a[i]] = c[a[i]] + 1; } //统计数a[i]前面有多少个小于a[i]的数 for(int i=1;i<c.length;i++){ c[i] = c[i] + c[i-1]; } //将a[i]插入到相应的b[i]中 for(int i=a.length-1;i>=0;i--){ b[c[a[i]]-1] = a[i]; c[a[i]] = c[a[i]]-1; } return b;}}

对上面的代码,做点点优化

/** * @author WuKung * @csdnURL http://blog.csdn.net/wu_kung/ * @createdDate 2014-4-18 下午1:32:53 */public class CountingSort {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[] a={2,3,5,7,8,3,5,2,4};int[] b=count_sort(a);for(int i:b){System.out.print(i+" ");}}public static int[] count_sort(int[] a){int[] b = new int[a.length];int max = a[0]; int min = a[0];for(int i:a){if(max<i){max = i;}if(min>i){min = i;}}int k = max-min+1;int[] c = new int[k];for(int i=0;i<a.length;i++){c[a[i]-min] += 1; }for(int i=1;i<c.length;i++){c[i] = c[i] + c[i-1];}for(int j=a.length-1;j>=0;j--){b[--c[a[j]-min]] = a[j];//c[a[j]] --;}return b;}}




15 0