Merge-sort algorithm throws "list index out of range" for big numbers

  algorithm, list, merge, python

First of all, I will start by saying that I’m learning python at the moment.
I’m trying to understand the merge-sort by building the program myself. So far, I’ve done a function that merge two list. The problem is that this function works just fine for small numbers(like 1-70 or something like this) but if I want to go crazy throwing a number like 100 it will throw me a "list index out of range" error

def GenerateArray(n):
    randomlist=[]
    for i in range(0,n):
        n = random.randint(-100,100)
        randomlist.append(n)
    return randomlist

def Merge(a,b):
    c = list()
    i, j, k = 0, 0, 0
    longestList = max(len(a), len(b))
    if len(a) > len(b):
        while i < longestList:
            if a[i] == b[j]:
                c.append(a[i])
                i = i + 1
                j = j + 1
            elif j == len(b) - 1:
                i = i + 1
                j = 0
            else:
                j = j + 1
    else:
        while j <= longestList:
            if b[j] == a[i]:
                c.append(a[i])
                i = i + 1
                j = j + 1
            elif i == len(a) - 1:
                j = j + 1
                i = 0
            else:
                i = i + 1
    uniques = []
    for i in c:
        if i not in uniques:
            uniques.append(i)
    c = uniques
    print(c)


n=int(input("nHow many items would you like your first array to have? "))
a=GenerateArray(n)
print("The first array is: ")
print(a)
n=int(input("nHow many items would you like your second array to have? "))
b=GenerateArray(n)
print("The second array is: ")
print(b)
print("Merging the arrays...")
Merge(a,b)

Source: Python Questions

LEAVE A COMMENT