0
def mergeSort(Data):
# result = []
# This location can't operate result.append(group1(pop(0)) at the while loop.

if len(Data) <= 1:
    return Data

mid = len(Data) // 2

group1 = mergeSort(Data[:mid])
group2 = mergeSort(Data[mid:])

result = []
# Why this postion?

while group1 and group2:
    if group1[0] < group2[0]:
        result.append(group1.pop(0))
    else:
        result.append(group2.pop(0))

while group1:
    result.append(group1.pop(0))
while group2:
    result.append(group2.pop(0))
return result

Hello. I have a doubt about this code. I defined function for making merge sorting algorithm. But the empty list for inserting values couldn't working when I input forward. I don't under reason why this list should be input in front of the while loop. please let me know.

4
  • You need to initialize the variable result as a list before you can append to it - stackoverflow.com/questions/30858392/… Commented May 5, 2021 at 7:47
  • It works just fine for me. You should recheck it personally @Ian. Also, make sure the indentations are right. Commented May 5, 2021 at 7:49
  • How are you calling the function? Commented May 5, 2021 at 7:53
  • First location can't operate result.append(group1(pop(0)) because when you call function, python don't know what is group1? Besides, I test a case array [3, 2, 1] and your algorithm print out [1, 3, 2]. If I change array to [3, 2, 1, 4], output is right [1, 2, 3, 4]. Commented May 5, 2021 at 8:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.