merge two arraylist lists in list1 while it remain sorted

后端 未结 7 876
忘了有多久
忘了有多久 2021-01-16 11:00

In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 remains sorted.

I write my code but it

相关标签:
7条回答
  • 2021-01-16 11:42

    You only need one for loop assuming both lists are sorted:

    public static void merge(List<Integer> l1, List<Integer> l2) {
        for (int index1 = 0, index2 = 0; index2 < l2.size(); index1++) {
            if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
                l1.add(index1, l2.get(index2++));
            }
        }
    }  
    

    If l2 isn't sorted, you need two loops:

    public static void merge(List<Integer> l1, List<Integer> l2) {
        for (int index2 = 0; index2 < l2.size(); index2++) {
            for (int index1 = 0; ; index1++) {
                if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
                    l1.add(index1, l2.get(index2));
                    break;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题