计数排序

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

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值