Counting Sort implementation

819 Views Asked by At

Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!

In my code k is the highest value in the input array.

Code:

public static void main(String[] args) {
    int [] arrayOne = {0,1,1,3,4,5,3,0};
    int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
    System.out.println(Arrays.toString(arrayOne));
    countingSort(arrayOne, output, 5);
    System.out.println(Arrays.toString(output));

}

public static void countingSort(int[] input, int[] output , int k){
    int [] temp = Arrays.copyOf(input, k+1);

    for (int i = 0; i <= k; i++){
        temp[i] = 0;
    }

    for (int j = 0; j <= input.length - 1; j++){
        temp[input[j]] = temp[input[j]] + 1;
    }

    for (int i = 1; i <= k; i++){
        temp[i] = temp[i] + temp[i-1];
    }

    for (int j = input.length; j >= 1; j--){
        output[temp[input[j]]] = input[j];
        temp[input[j]] = temp[input[j]] - 1;
    }
}
4

There are 4 best solutions below

1
On

The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.

So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].

To fix this change your first loop to:

for (int i = 0; i < k; i++){

In the last loop you will get the same exception cause input[8] doesn't exist.

1
On

this may help but try using the Arraya.sort() method. e.g:

//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers 
// using Arrays.sort(). It by default sorts in 
// ascending order 
import java.util.Arrays; 

public class SortExample 
{ 
    public static void main(String[] args) 
    { 
        // Our arr contains 8 elements 
        int[] arr = {13, 7, 6, 45, 21, 9, 101, 102}; 

        Arrays.sort(arr); 

        System.out.printf("Modified arr[] : %s", 
                          Arrays.toString(arr)); 
    } 
}

example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

2
On
import java.util.Arrays;

public class CountingSort {
    public static void main(String[] args) {
        int[] input = {0,1,1,3,4,5,3,0};
        int[] output = new int[input.length];
        int k = 5; // k is the largest number in the input array
        System.out.println("before sorting:");
        System.out.println(Arrays.toString(input)); 
        output = countingSort(input, output, k);
        System.out.println("after sorting:");
        System.out.println(Arrays.toString(output));
    }

    public static int[] countingSort(int[] input, int[] output, int k) {
        int counter[] = new int[k + 1]; 
        for (int i : input) { counter[i]++; } 
        int ndx = 0; 
        for (int i = 0; i < counter.length; i++) {
            while (0 < counter[i]) { 
                output[ndx++] = i;
                counter[i]--; 
            }
        }
        return output;
    }
}

Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html

0
On

As per algorithm following implementation, I have prepared for the count sort technique

public static int[] countSort(int elements[]) {
    int[] sorted = new int[elements.length+1];
    int[] range = new int[getMax(elements)+1];
    for(int i=0;i<range.length;i++) {
        range[i] = getCount(i, elements);
        try {
            range[i] = range[i]+range[i-1];
        }catch(ArrayIndexOutOfBoundsException ae) {
            continue;
        }
    }       

    for(int i=0;i<elements.length;i++) {
        sorted[range[elements[i]]] = elements[i];
        range[elements[i]] = range[elements[i]]-1;
    }       
    return sorted;
}

public static int getCount(int value,int[] elements) {
    int count = 0;
    for(int element:elements) {
        if(element==value) count++;
    }
    return count;
}

public static int getMax(int elements[]) {
    int max = elements[0];
    for(int i=0;i<elements.length;i++) {
        if(max<elements[i]) {
            max = elements[i];
        }           
    }
    return max;
}

Please review and let me know if any feedback and it is more helpful. Note : Non-negative no won't support in the above implementation. don't use 0th index of the sorted array.