E
E
electrokeller2014-04-09 19:10:23
Java
electrokeller, 2014-04-09 19:10:23

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

I use sorting by counting.
My decision:
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;  
        }  
    }  
  }
}

But it throws an error:
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)


Why does this code not work, because there is no way out of bounds there?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
R
Rsa97, 2014-04-10
@electrokeller

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++) {

V
verwolfdotss, 2014-04-09
@verwolfdotss

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.

V
verwolfdotss, 2014-04-09
@verwolfdotss

I also advise you to view at a slow speed, for a better understanding of the algorithm.
Link

S
schroeder, 2014-04-09
@schroeder

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?

V
verwolfdotss, 2014-04-09
@verwolfdotss

And what about the max parameter? As I understand it, there should be 10, but the number of entered elements will be there, no?

In fact, if I, for example, enter two numbers
6 8 ,
then the array will be 2 in size,
and I will refer to the 6th and 8th cell of the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question