UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 10.1-demos/ merge sort.py
#!/usr/bin/env python3
from random import choices,random

def merge(A,B):
    i = 0;
    j = 0;
    out = [];
    
    while (i < len(A) and j < len (B)):
        if (A[i] < B[j]):
            out.append(A[i])
            i+=1
        else:
            out.append(B[j])
            j+=1

    if (j<len(B)):
        out.extend(B[j:])
    elif (i<len(A)):
        out.extend(A[i:])

    return out;

def merge_sort(A):
    n = len(A)
    if (n <= 1):
        return A

    split = max(n//2,1)
    left=merge_sort(A[0:split])
    right=merge_sort(A[split:])
    return merge(left,right)

if __name__ == "__main__":
    A = choices(range(0,100),k=11)
    print("A=",A);
    print("sort(A)=",merge_sort(A));