索引越界Java合并排序?

问题描述 投票:-2回答:2

我正在研究合并排序算法。以下是我到目前为止所写的内容。问题是,当我尝试运行它以查看它是否正常工作时,我在带有注释的if语句中获得了索引超出范围的错误。

为什么我在旁边评论的行上得到索引?

我知道这个错误意味着什么,但我无法解读为什么它的出界。

public class MergeSort {

    public static int mergeSort(int[] list1, int[] list2) {
        int[] list3 = new int[list1.length + list2.length];
        int smallest1 = list1[0];
        int smallest2 = list2[0];
        int position1 = 0;
        int position2 = 0;

        for (int i = 0; i<list1.length + list2.length; i++) {
                for (int j =0; j<= list1.length; j++) {
                    if (list1[j] < smallest1) { //here index out of bouds
                        smallest1 = list1[j];
                        System.out.print(list1[j]+"smallest value");
                        position1 = j;
                    }
                }
                for (int l =0; l<= list2.length; l++) {
                    if (list2[l] < smallest2) {
                        smallest2 = list2[l];
                        System.out.print(list2[l]+"smallest value");
                        position2 = l;
                    }
                }

                if (smallest1< smallest2) {
                    list3[i] = smallest1;
                } else if (smallest2< smallest1) {
                    list3[i] = smallest2;
                }
        }
        //print the array
        for (int l =0; l<= list2.length; l++) {
            System.out.print("new array 3" + list3[l]);
        }
        return 1;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] list1 = {17, 22, 35, 42, 60};
        int[] list2 = {9, 14, 66};
        int[] list3;

        mergeSort(list1, list2);
    }

}   
java arrays sorting indexoutofboundsexception mergesort
2个回答
1
投票

索引从0开始,这意味着当list1.length = 5时,索引可以是0到4 更改

for (int j =0; j<= list1.length; j++)

for (int j =0; j < list1.length; j++)

0
投票
  • 这是因为你的for循环条件是<=。尝试使用<
© www.soinside.com 2019 - 2024. All rights reserved.