简体   繁体   English

冒泡排序字符串数组

[英]bubble sort string array

I'm trying to use a bubble sort to alphabetize an array that I've read into a program. 我正在尝试使用冒泡排序将输入到程序中的数组按字母顺序排列。 The code compiles without error but I get an Array Index Out Of Bounds Exception on my 'if' construct when I try to run the program. 该代码编译没有错误,但是当我尝试运行该程序时,在“ if”构造上出现了数组索引超出界限异常。 I have initialized int i to 0 to account for the first index of the array so I think my error is elsewhere. 我已经将int i初始化为0以说明数组的第一个索引,因此我认为我的错误在其他地方。 I'm not asking anyone to write code for me, just maybe a point in the right direction. 我并不是在要求任何人为我编写代码,而只是向正确的方向迈出了一步。 Thanks for any help. 谢谢你的帮助。

public static String[] bubbleSort(String[] inL)
{
    String temp;
    int i = 0, passNum;

    for(passNum = 1; passNum <= (inL.length); i++)  // controls passes through bubble sort
    {
        if(inL[i].compareToIgnoreCase(inL[i + 1]) < 0)
        {
            temp = inL[i];
            inL[i] = inL[i + 1];
            inL[i + 1] = temp;
        }
    }

    return inL; // returns sorted array 
} // end bubbleSort method

You compare passNum instead of i against the length of the array. 您将passNum而不是i与数组的长度进行比较。 Since passNum is never modified, the loop condition is always true, and i gets incremented until it exceeds the range of the array. 由于passNum从未修改,因此循环条件始终为true,并且i会递增直到它超出数组的范围。

Even if this particular issue is resolved, you may still run into problems with off-by-one errors with your current implementation. 即使此特定问题得到解决,您当前的实现仍可能会遇到一个一次性错误的问题。 Consider whether you should compare i against inL.length - 1 . 考虑是否应该将iinL.length - 1进行比较。

You never increment passNum so i continues incrementing forever. 您永远不会增加passNum所以i永远继续增加。 Also, array indexing in Java is based at 0. That means that the largest valid index is inL.length - 1 . 另外,Java中的数组索引基于0。这意味着最大的有效索引为inL.length - 1 Since the body of your loop accesses inL[i+1] , you should arrange your code so that i never exceeds inL.length - 2 . 由于循环的主体访问inL[i+1] ,因此应安排代码,以使i永远不会超过inL.length - 2 At a minimum, you should change <= to < in the for loop termination test. 至少应在for循环终止测试中将<=更改为< (However, the logic of your comparison and incrementing escapes me; you need to fix that as well.) (但是,您进行比较和递增的逻辑使我无所适从;您也需要解决该问题。)

Array.length stores the total length of an array, starting counting at 1. Array.length存储数组的总长度,从1开始计数。

The first index in an array however is 0, meaning that the last index is length-1 . 但是,数组中的第一个索引为0,这意味着最后一个索引为length-1

adjust your check in your for-loop to fix the error 在for循环中调整检查以修复错误

您的问题是passNum <= (inL.length)它应该是passNum < (inL.length)因为0是Java中数组的第一个索引

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

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