My program for counting sort always shows this error- Index 9 out of bounds for length 9

75 Views Asked by At

I have been writing the below mentioned code for the problem and it always shows me the error that my index is out of bounds for my length. I have tried printing the size and it is comparitively very large.

import java.util.*;
class Main {
    public static void countingSort(int numbers[]) {
    //    int n = numbers.length - 2;

       int largest=Integer.MIN_VALUE;
       for (int i=0;i<numbers.length;i++){
           largest=Math.max(largest,numbers[i]);
       }
       int count[]=new int[largest+1];
        System.out.println(count.length+"= length\n");
       for (int i=0;i<count.length;i++)
           count[numbers[i]]++;
       int j=0;
       for (int i=0;i<count.length;i++){
           while(count[i]>0){
               numbers[j]=i;
               j++;
               count[i]--;
           }
       }
       for(int i=0;i<numbers.length;i++)
            System.out.println(numbers[i]);
    }
    public static void main(String args[]) {
        int numbers[] ={5,8,7,19,25,4,2,3,1};
       countingSort(numbers);

    }


1

There are 1 best solutions below

1
m3ow On

It is because your variable "numbers" only holds 9 values.

for (int i=0;i<count.length;i++)
       count[numbers[i]]++;

This for loop will iterate depending on the size of your variable "count". In your case, the variable "count" will hold 26 values. It throws an error when the variable "numbers" is being accessed with an index beyond its size.