Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return value is 0 when use Mergesort in Python?

I am making merge sort code but it does not sort. Do you see what's wrong with it?

def mergeSort(L):
   if len(L) == 1:
       return L
   else:
       # divide
       L1 = mergeSort(L[0:round(len(L)/2)])
       L2 = mergeSort(L[round(len(L)/2):len(L)])
    
       # merge
       i = 0
       j = 0
       K = []
       while i < len(L1) and j < len(L2):
           if L1[i] < L2[j]:
               K.append(L1[i])
               i=i+1
           else:
               K.append(L2[j])
               j=j+1
       return K

Input:

L = [1,2,5,7,8,0,10,21,32,53,16,16,48,59,64,53,75,52,42,21,98,76‌​] 

Output:

L = [0]
like image 730
RyanC Avatar asked Dec 14 '22 20:12

RyanC


1 Answers

while i < len(L1) and j < len(L2):

This doesn't look right to me. With this condition, the loop will end once either of i or j reaches the end of their respective list. There might still be elements in the other list that never get iterated over, as a result.

Try changing that and to an or, and add some checking to make sure that inter-list comparison only happens when neither list has been completely iterated yet:

    while i < len(L1) or j < len(L2):
        if i < len(L1) and (j == len(L2) or L1[i] < L2[j]):
            K.append(L1[i])
            i=i+1
        else:
            K.append(L2[j])
            j=j+1

Now your code outputs [0, 1, 2, 5, 7, 8, 10, 16, 16, 21, 21, 32, 42, 48, 52, 53, 53, 59, 64, 75, 76, 98].

like image 94
Kevin Avatar answered Dec 26 '22 03:12

Kevin