简体   繁体   English

为什么这种排序算法不起作用?

[英]Why does this sort algorithm not work?

public static int[] organizaC(int[] v) {
    int i, temp = 0;
    if (v.length > 0) {
        for (i = 0; i < v.length; i++) {
            if (v[i] > v[i + 1]) {
                temp = v[i];
                v[i] = v[i + 1];
                v[i + 1] = temp;
                i = 0;
            }
        }
        return v;
    } else {
        return null;
    }
}

I'm getting an ArrayOutofBoundsIndex exception when trying to use this function but the IDE won't let me use the debugger.尝试使用此函数时出现ArrayOutofBoundsIndex异常,但 IDE 不允许我使用调试器。 Anyone knows what is happening?有谁知道发生了什么? Am I causing some buggy loop?我是否造成了一些错误循环?

Imagine what happens when i equals v.length - 1 , your if statment :想象一下当i等于v.length - 1时会发生什么,你的 if 语句:

if(v[v.length-1] > v[v.length-1+1])

you try to acces your array at index v.lenght but as arrays' indices go from 0 to v.length-1 , you are out of bounds!您尝试在索引v.lenghtv.lenght您的数组,但由于数组的索引从0v.length-1 ,您超出了界限!

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

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