Python progarm for Merge Sort
kw.py
def merge_sort(nlist):
    if len(nlist) > 1:
        mid = len(nlist) // 2
        lefthalf = nlist[:mid]
        print(" Left Split:", lefthalf)
        righthalf = nlist[mid:]
        print("Right Split:", righthalf)

        merge_sort(lefthalf)
        merge_sort(righthalf)
        i = j = k = 0

        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                nlist[k] = lefthalf[i]
                i += 1
            else:
                nlist[k] = righthalf[j]
                j += 1
            k += 1

        while i < len(lefthalf):
            nlist[k] = lefthalf[i]
            i += 1
            k += 1
            print(" Left Merge:", nlist)

        while j < len(righthalf):
            nlist[k] = righthalf[j]
            j += 1
            k += 1
            print("Right Merge:", nlist)

nlist = [12, 1024, -2048, 0, -1, 95, 987]
merge_sort(nlist)
print(nlist)
Output
kodingwindow@kw:~$ python3 kw.py
Left Split: [12, 1024, -2048]
Right Split: [0, -1, 95, 987]
 Left Split: [12]
Right Split: [1024, -2048]
 Left Split: [1024]
Right Split: [-2048]
 Left Merge: [-2048, 1024]
Right Merge: [-2048, 12, 1024]
 Left Split: [0, -1]
Right Split: [95, 987]
 Left Split: [0]
Right Split: [-1]
 Left Merge: [-1, 0]
 Left Split: [95]
Right Split: [987]
Right Merge: [95, 987]
Right Merge: [-1, 0, 95, 987]
Right Merge: [-1, 0, 95, 987]
 Left Merge: [-2048, -1, 0, 12, 95, 987, 1024]
[-2048, -1, 0, 12, 95, 987, 1024]
kodingwindow@kw:~$ 
Advertisement