Sorting - Merge sort - Functions

# Merge sort

# Function to merge sorted lists
def merge(a, b):
    c = []
    while (len(a) != 0 and len(b) != 0):
        if a[0] < b[0]:
            c.append(a[0])
            a.remove(a[0])
        else:
            c.append(b[0])
            b.remove(b[0])
    if(len(a) == 0):
        c = c + b
    else:
        c += a
    return c

# Function - create sublists
def mergesort(L1):
    if len(L1) == 0 or len(L1) == 1:
        return L1
    else:
        middle = len(L1)//2
        a = mergesort(L1[:middle])
        b = mergesort(L1[middle:])

    return merge(a,b)

# Read elements and create list

no_of_terms = int(input("Enter number of terms : "))
Original_List = []

for idx in range(0, no_of_terms, 1):
    ele = int(input("Enter element : "))
    Original_List.append(ele)

Sorted_list = mergesort(Original_List)

print("Original list :", Original_List)
print("Sorted List :", Sorted_list)

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu