I am a high school student doing a simple merge sort algorithm, but I encountered below error message. Help is much appreciated!
File "main.py", line 22, in mergesort if l_list[i] <= r_list[j]:
TypeError: '<=' not supported between instances of 'int' and 'list'
Here's my code:
list = [1, 3, 5, 6, 2]
def mergesort(list):
n = len(list)
if n <= 1:
return
mid_cut = n // 2
l_list = list[:mid_cut]
r_list = list[mid_cut:]
mergesort(l_list)
mergesort(r_list)
i = 0
j = 0
list.clear()
while i < len(l_list) and j < len(r_list):
if l_list[i] <= r_list[j]:
list.append(l_list[i])
i = 1
else:
list.append(r_list[j])
j = 1
if i < len(l_list):
list.append(l_list[i:])
else:
list.append(r_list[j:])
mergesort(list)
I tried extracting items from two local lists and compare them, but one of the "item" turned into a list somehow.
CodePudding user response:
In this code, you append slices to list.
if i < len(l_list):
list.append(l_list[i:])
else:
list.append(r_list[j:])
Use list.extend(...) instead:
if i < len(l_list):
list.extend(l_list[i:])
else:
list.extend(r_list[j:])
CodePudding user response:
list is reserved word in python, name it something other than list it may be conflicting with your code.
Have a look at this.
def mergeSort(array):
if len(array) > 1:
# r is the point where the array is divided into two subarrays
r = len(array)//2
L = array[:r]
M = array[r:]
# Sort the two halves
mergeSort(L)
mergeSort(M)
i = j = k = 0
# Until we reach either end of either L or M, pick larger among
# elements L and M and place them in the correct position at A[p..r]
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i = 1
else:
array[k] = M[j]
j = 1
k = 1
# When we run out of elements in either L or M,
# pick up the remaining elements and put in A[p..r]
while i < len(L):
array[k] = L[i]
i = 1
k = 1
while j < len(M):
array[k] = M[j]
j = 1
k = 1
# Print the array
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
mergeSort(array)
print("Sorted array is: ")
printList(array)