Answer the question
In order to leave comments, you need to log in
How to avoid array overflow?
Given task:
The first line contains the number n (1≤n≤10000), the second - n natural numbers not exceeding 10. You need to output a sequence of these numbers ordered in non-decreasing order (numbers must be separated by spaces).
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] sourceNumbers = new int[n];
for (int i = 0; i < n; i++) {
sourceNumbers[i] = in.nextInt();
}
in.close();
countingSort(sourceNumbers, n);
for (int i = 0; i < n; i++) {
System.out.print(sourceNumbers[i] + " ");
}
}
public static void countingSort(int[] arr, int max) {
int i, j, b = 0;
int[] c = new int[max];
for (i = 0; i < max; i++) c[i] = 0;
for (i = 0; i < arr.length; i++) {
c[arr[i]] = c[arr[i]] + 1;
b = 0;
}
for (j = 0; j < max; j++) {
for (i = 0; i < c[j]; i++) {
arr[b] = j;
b = b + 1;
}
}
}
}
Failed test #1. Run time error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Main.countingSort(main.java:24)
at Main.main(main.java:12)
Answer the question
In order to leave comments, you need to log in
It is necessary to call the sorting function as an countingSort(sourceNumbers, 10);
Array, declare as int[] c = new int[max+1];
Well, cycles must be up to max inclusive
for (i = 0; i <=max; i++) c[i] = 0;
...
for (j = 0; j <= max; j++) {
Why
?
As far as I understand counting sort, if given a number from 0 to 10 inclusive, then this array should be 11 in size.
I also advise you to view at a slow speed, for a better understanding of the algorithm.
Link
for (i = 0; i < max; i++) c[i] = 0;
it is not necessary, there are zeros anyway.
And what about the max parameter? As I understand it, there should be 10, but the number of entered elements will be there, no?
And what about the max parameter? As I understand it, there should be 10, but the number of entered elements will be there, no?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question