简体   繁体   English

冒泡排序:编译错误

[英]Bubble sort : compilation error

I try to program some sorting, even though I don't have syntax or logic error in my code, while compiling I get an exception which seems to be related to the sorting method : 我尝试对一些排序进行编程,即使我的代码中没有语法或逻辑错误,在编译时也会出现异常,该异常似乎与排序方法有关:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at triBulle.bulle(triBulle.java:35)
at triBulle.main(triBulle.java:64)

Here's my code : 这是我的代码:

public static void bulle(int[] T)
{
    int n = T.length;
    boolean echange = true ;

    while((n>0) && (echange))
    {
        echange = false ;
        for(int j = 0 ; j<n ; j++)
        {
            if(T[j] >T[j+1])
            {
                int tmp = T[j];
                T[j] = T[j+1];
                T[j+1] = tmp;
                echange = true ;
            }
        }
        n = n-1;
    }

}

Thanks to check this out. 感谢您检查一下。

Someone correct me if I am wrong, but I am rather sure that, in java, an array with elements [0], [1], and [2] has a length of 3. So in your while-loop, if j is equal to length-1 then that is the last index. 如果我错了,请有人纠正我,但是我可以肯定,在Java中,包含元素[0],[1]和[2]的数组的length为3。因此在while循环中,如果j为等于length-1 ,则为最后一个索引。 Therefore, when [j+1] gets called, you get an ArrayIndexOutOfBoundsException 因此,当[j+1]被调用时,您将获得ArrayIndexOutOfBoundsException

One way to fix it would be 解决它的一种方法是

for(int j = 1 ; j<n ; j++)
    {
        if(T[j-1] >T[j])

Or 要么

for(int j = 0 ; j<n-1 ; j++)
    {
        if(T[j] >T[j+1])

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

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