#!/usr/bin/python3

# SI 335: Computer Algorithms
# Unit 2

import random
import sys
from copy import copy

def swap(A, i, j):
    A[i], A[j] = A[j], A[i]

def selectionSort(A):
    for i in range(0, len(A)-1):
        m = i
        for j in range(i+1, len(A)):
            if A[j] < A[m]: 
                m = j
        swap(A, i, m)

def insertionSort(A):
    for i in range(1, len(A)):
        j = i - 1
        while j >= 0 and A[j] > A[j+1]:
            swap(A, j, j+1)
            j = j - 1

def selectionSortRec(A, start=0):
    if (start < len(A) - 1):
        m = minIndex(A, start)
        swap(A, start, m)
        selectionSortRec(A, start + 1)

def minIndex(A, start=0):
    if start >= len(A) - 1:
        return start
    else:
        m = minIndex(A, start+1)
        if A[start] < A[m]: 
            return start
        else: 
            return m

def mergeSort(A):
    if len(A) <= 1: 
        return A
    else:
        m = len(A) // 2
        B = A[0 : m]
        C = A[m : len(A)]
        mergeSort(B)
        mergeSort(C)
        A[:] = merge(B, C)

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

# This is provided for testing purposes.
def randomArray(size, maxval):
    return random.sample(range(maxval), size)

def sortTest(algs = (selectionSort, insertionSort, selectionSortRec, mergeSort)):
    sys.setrecursionlimit(10000)
    allgood = True
    data = randomArray(500, 1000000)
    for alg in algs:
        good = True
        thisdata = copy(data)
        alg(thisdata)
        # check if it's sorted
        for i in range(1, len(thisdata)):
            if thisdata[i] < thisdata[i-1]:
                good = False
        if set(thisdata) != set(data):
            good = False
        if not good:
            print("FAILED CHECK FOR", alg.__name__)
            allgood = False
    if allgood:
        print("Passed all sorting checks")

if __name__ == '__main__':
    sortTest()
