Search code examples
pythonmergesort

Divide and Conquer Sorting Algorithm Difficulty


Merge Sort Implementation Is having difficulty giving the correct output:

def merge_sort(a):
    # array of 1 item or less returns the same array
    if len(a) <= 1:
        return a
    # index for middle of array
    m = math.floor(len(a) / 2)
    # Recursive method for dividing and sorting original array into smaller 
    # arrays
    a0 = merge_sort(a[0:m])
    a1 = merge_sort(a[m:])
    merge(a0, a1, a)
    return a

def merge(a0, a1, a):
    # Indices for arrays a1 and a0
    i0 = 0
    i1 = 0
    for i in range(len(a)):
        # Array no longer contains elements not already sorted into Array a
        if i0 == len(a0):
            a[i] = a1[i1]
            i1 += 1
        # Array no longer contains elements not already sorted into Array a
        elif i1 == len(a1):
            a[i] = a0[i0]
            i0 += 1
        # Comparing Arrays a1 and a0, then adding smaller element to 
        # original Array a
        elif a[i0] < a[i1]:
            a[i] = a0[i0]
            i0 += 1
        else:
            a[i] = a1[i1]
            i1 += 1

The logic is correct but there may be something wrong with my indices or references that I am just not catching. What may be wrong with my code and how may I fix it?


Solution

  • def merge(a0, a1, a):
        i0 = 0
        i1 = 0
        for i in range(len(a)):
            if i0 == len(a0):
                a[i] = a1[i1]
                i1 += 1
            elif i1 == len(a1):
                a[i] = a0[i0]
                i0 += 1
            elif a0[i0] < a1[i1]:
                a[i] = a0[i0]
                i0 += 1
            else:
                a[i] = a1[i1]
                i1 += 1
    

    mistake happens at merge(),you should compare a0 and a1 instead of a.