Counting sort

         You can comprehend this problem from two different points of view.

         Case 1: For an element x in an array, to check how many elements is less than x, after we got that message, we can put x to the right position. For example, if we have 17 elements less than x, the right position for x is 18.

    Case 2: You can also comprehend this problem from the other point of view. If an element values vi appears x times, you should put x to the position vi in the array C.

When you finish the counting, rearrange the array A according array C.

Here I only implement this algorithms according case 2, because it has a smaller space complexity, just as follow:  

1.      Before you count the array, you should know the maximum and minimum first.

2.      Create a new array C, its length is maximum-minimum+1.

3.      Counting the element in the array, if the same element appears x times, then put x to the array C and the position is the element’s value.

4.      Loop through array C and rearrange the array A, if an element in array C have a value C[i], that means from the current position you want to process to the next C[i] position of array A, they have the same value i.

 

The time complexity of the count sort is O(n+k),so if the k is not too big, you will gain a higher efficiency.

 

The following is the implement of counting sort by java.

public int[] countSort(int[] A, int max,int min){
    int[] C = new int[max-min+1];
    for(int i = 0;i < max-min;i++) {
        C[i] = 0;
    }
    for(int i = 0;i < A.length;i++){
        C[A[i]-min] = C[A[i]-min]+1;
   }
    int index = 0;
    for(int i = 0;i < C.length;i++){
        while(C[i] > 0){
            A[index] = i+min;
            index++;
            C[i]--;
        }
    }
    return A;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值