Tuesday, October 27, 2020

Merge Sort in Python

def mergesort(dataset):

    l = len(dataset)            # calculate length of dataset
    if (l > 1):                 # if dataset has elements

        mid = l // 2            # find the mid point of the dataset/array
        left = dataset[:mid]    # create left array
        right = dataset[mid:]   # create right array

        mergesort(left)         # call mergesort on left array
        mergesort(right)        # call mergesort on right array

        i = j = k = 0           # index for left, right and result array respectively

        while i < len(left) and j < len(right): # if left array at position i
            if left[i] < right[j]:              # has element smaller than right array at position j
                dataset[k] = left[i]            # assign the element to result array
                i += 1                          # increment i
            else:
                dataset[k] = right[j]           # else add the element from right array to result array
                j += 1                          # increment j
                        
            k += 1                              # increment the value of k


        while i < len(left):    # if left still has elements add them to result array
            dataset[k] = left[i]
            i += 1
            k += 1

        while j < len(right):   # if left still has elements add them to result array
            dataset[k] = right[j]
            j += 1
            k += 1

def main():
    items = list()
    s = int(input("Enter size of array : "))
    for i in range(s):
        items.append(int(input(f"enter element at positin {i+1} : ")))

    print(items)
    mergesort(items)
    print(items)

if __name__ == "__main__":
    main()