Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

[Java]Why does the initial for loop starts with index i=0 post the break in else condition

I am trying to implement a solution to merge two sorted arrays to a single sorted array. I tried to implement a code but it does not work. The issue that I am seeing here is after my outer for loop reaches the limit of array2.length(), it still gets started from i=0. Can someone please help explain whats wrong in this piece of code?

List<Integer> mergedArray = new ArrayList<>();
int counter = 0;

public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
    
    for (int i = 0; i < array1.size(); i++) {

        for (int j = counter; j < array2.size(); j++) {
            if (array1.get(i) > array2.get(j)) {
                mergedArray.add(array2.get(j));
                counter++;
            } else {
                mergedArray.add(array1.get(i));
                System.out.println("i "  +i);
                break;
            }

        }
    }

    return mergedArray;
}
question from:https://stackoverflow.com/questions/66045218/javawhy-does-the-initial-for-loop-starts-with-index-i-0-post-the-break-in-else

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One problem I see with the code is when the two arrays do not have same length. In either case of (array1.length > array2.length or reverse) the remaining elements of longer array will not be processed. So if you add a more code at end of this the loops to deal with that case, this might work well!

public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
    List<Integer> mergedArray = new ArrayList<>();
    int counter = 0, i = 0, j = 0;
    
    for (i = 0; i < array1.size(); i++) {

        for (j = counter; j < array2.size(); j++) {
            if (array1.get(i) > array2.get(j)) {
                mergedArray.add(array2.get(j));
                counter++;
            } else {
                mergedArray.add(array1.get(i));
                System.out.println("i "  +i);
                break;
            }

        }
    }

    // More code here
    if (j==array2.size()){//copy rest of array1 into mergedArray}
    if (i==array1.size()){//copy rest of array2 into mergedArray}


    return mergedArray;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...