Question: Please fix the following Java code so the counting sort program stops throwing array index out of bounds exception (**Note it is necessary the array
Please fix the following Java code so the counting sort program stops throwing array index out of bounds exception(**Note it is necessary the array can handle large inputs(> 1000) without creating array index out of bounds exceptions)
import java.util.*;
public class CountingSort {
static int[] countingSort(int[] array) {
int n = array.length;
int[] count = new int[1000];
for (int i = 0; i < n; i++){
count[i] = 0;
}
for (int i = 0; i < n; i++){
count[array[i] - 1]++;
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Read the number of inputs
int n = in.nextInt();
int[] array = new int[n];
// Read the inputs into an array
for(int i = 0; i < n; i++){
array[i] = in.nextInt();
}
// result will contain the counts of the numebrs
int[] result = countingSort(array);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
}
System.out.println();
in.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
