Merge two sorted arrays using for loop is missing the last item

Question:

I m new to dealing with algorithms and my challenge was to merge two sorted lists into one using for loop not while loop. I got stuck at determining the end of the list:

list1=[1,2,4]
list2=[1,3,4,6]

def mergeTwoLists(list1: list, list2:list) -> list:
     l = 0
     r = 0
     lRange = len(list1)-1
     rRange = len(list2)-1

     total_range = (len(list1)+len(list2))-1
     merger = []

     for i in range(total_range):
         
         if list1[l]<=list2[r]:
             
             merger.insert(i,list1[l])
             if l<lRange:
                 l+=1
            
         elif list1[l]>list2[r]:
             
             merger.insert(i,list2[r])
             if r<rRange:            
                 r+=1
     return(merger)

It returns [1,1,2,3,4,4] and missing the last value 6.

Asked By: Mike Curtis

||

Answers:

You’re missing the last element because you subtract 1 when creating total_range.

You need to test which index is still within range inside the loop. You can only compare elements while both indexes are in range for their respective lists. Once you reach the end of one of the lists, just copy the rest of the other list to the result.

def mergeTwoLists(list1: list, list2:list) -> list:
     l = 0
     r = 0
     lRange = len(list1)
     rRange = len(list2)

     total_range = lRange + rRange
     merger = []

     for i in range(total_range):
         if l < lRange and r < rRange:
             if list1[l]<=list2[r]:
                 merger.append(list1[l])
                 l+=1
             elif list1[l]>list2[r]:
                 merger.append(list2[r])
                 r+=1
         elif l < lRange:
            merger.extend(list1[l:])
            break
         else:
            merger.extend(list2[r:])
            break

     return(merger)

list1=[1,2,4]
list2=[1,3,4,6]
print(mergeTwoLists(list1, list2))
Answered By: Barmar

I saw some mistakes :

  • As Barmar said, you can use append() instead of insert()
  • you must remove the -1 in the definition of total_range
  • you must add conditions on l and r to be sure the element in list exists

Maybe this is what you are looking for :

list1 = [1, 2, 4]
list2 = [1, 3, 4, 6]


def mergeTwoLists(list1: list, list2: list) -> list:
    l = 0
    r = 0
    total_range = len(list1) + len(list2)
    merger = []

    for _ in range(total_range):
        if l < len(list1) and (r >= len(list2) or list1[l] <= list2[r]):
            merger.append(list1[l])
            l += 1

        else:
            merger.append(list2[r])
            r += 1
    return merger


print(mergeTwoLists(list1, list2))
# [1, 1, 2, 3, 4, 4, 6]
Answered By: Phoenixo

Following works for different kinds of lists. It gets items from the lists in an asynchronous manner and breaks out of loop when length of any one list is finished. Finally, it appends any excess items from the other list.

def mergeSortedLists(l1, l2): 
    outlist =[]; i=0; j=0; 
    while i<len(l1) and j<len(l2):
        a = l1[i]; b = l2[j]
        if a<b: 
            outlist.append(a); i+=1
        else: 
            outlist.append(b); j+=1
    outlist += l1[i:] + l2[j:]
    print(outlist)

Try:

list1=[1,2,4]
list2=[1,3,4,6,7]
mergeSortedLists(list1, list2)

output:

[1, 1, 2, 3, 4, 4, 6, 7]

Or:

list1=[1,2,3]
list2=[4,5,6,8]
mergeSortedLists(list1, list2)

Output:

[1, 2, 3, 4, 5, 6, 8]
Answered By: rnso