简体   繁体   English

计数排序问题

[英]Counting Sort issue

public static void countingSort(Integer[] a, int n) {
        //TODO
        //COMPLETE THIS METHOD
        int[] counter = new int[n+1];
        int[] sorted = new int[a.length];
        Arrays.fill(counter,0);
        // fills counter array with each number count
        for ( int i = 0 ; i < a.length; i++){
            counter[a[i]] += 1;
        } // adds n-1 index + n index
        for (int i = 1; i < counter.length; i++) {
            counter[i] = (counter[i] + counter[i-1]);
        } // shifts array to the right
        for (int i = counter.length-1; i > 0; i--) {
            counter[i] = counter[i-1];
        } // fills sorted array with the sorted out counts
        for (int i = 0; i < a.length; i++ ){
            sorted[counter[a[i]]] = a[i];
            counter[a[i]]++;
        }
    }

When ran it throws an array out of bound exception in the body of the first for loop.运行时,它会在第一个 for 循环的主体中抛出一个数组越界异常。 Im having trouble seeing it, if anyone could help guide me, it'd be much appreciated.我无法看到它,如果有人可以帮助指导我,将不胜感激。

When ran it throws an array out of bound exception in the body of the first for loop.运行时,它会在第一个 for 循环的主体中抛出一个数组越界异常。

That would be this:那将是这样的:

 for ( int i = 0; i < a.length; i++){ counter[a[i]] += 1; }

Im having trouble seeing it, if anyone could help guide me, it'd be much appreciated.我无法看到它,如果有人可以帮助指导我,将不胜感激。

An ArrayIndexOutOfBoundsException in that loop can only mean that you are exceeding the bounds of a or those of counter .该循环中的ArrayIndexOutOfBoundsException只能表示您超出了acounter的范围。 It is clear from inspection that you are not exceeding the bounds of a (though you could both eliminate that possibility and make the code a bit cleaner by switching to an enhanced for loop).从检查中可以清楚地看出,您没有超出a的范围(尽管您可以通过切换到增强for循环来消除这种可能性并让代码更简洁)。 The only remaining possibility is that you are exceeding the bounds of counter .唯一剩下的可能性是您超出了counter的范围。

The approach you've implemented supports only non-negative integers in the input array, and requires the method invoker to pass an upper bound on the element values as the second parameter.您实现的方法仅支持输入数组中的非负整数,并要求方法调用程序将元素值的上限作为第二个参数传递。 If those constraints are not satisfied then an exception such as you observe will be thrown.如果不满足这些约束,则会抛出您观察到的异常。

That is, if the exception is thrown where you say it is, then the problem is with the input.也就是说,如果在你说的地方抛出异常,那么问题出在输入上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM