-1

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

    }


Evg
  • 25,259
  • 5
  • 41
  • 83
Kdey
  • 9
  • 1
    Look at the error carefully. Which of your arrays is out of bounds? Think about which indexes you are using for which arrays. – tgdavies Nov 11 '22 at 03:41

1 Answers1

1

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.

m3ow
  • 151
  • 7