merge sort on list code example
Example 1: merge sort in python
def mergeSort(myList):
if len(myList) > 1:
mid = len(myList)
left = myList[:mid]
right = myList[mid:]
# Recursive call on each half
mergeSort(left)
mergeSort(right)
# Two iterators for traversing the two halves
i = 0
j = 0
# Iterator for the main list
k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
# The value from the left half has been used
myList[k] = left[i]
# Move the iterator forward
i += 1
else:
myList[k] = right[j]
j += 1
# Move to the next slot
k += 1
# For all the remaining values
while i < len(left):
myList[k] = left[i]
i += 1
k += 1
while j < len(right):
myList[k]=right[j]
j += 1
k += 1
myList = [54,26,93,17,77,31,44,55,20]
mergeSort(myList)
print(myList)
Example 2: merge sort in python
def mergesort(list1):
if len(list1) >1 :
mid = len(list1)
left_list = list1[:mid]
right_list = list1[mid:]
mergesort(left_list) #Using recursion down here for the sub list
mergesort(right_list) #Using recursion down here for the sub list
i = 0
j = 0
k = 0
while i<len(left_list) and j<len(right_list):
if left_list[i]< right_list[j]:
list1[k] = left_list[i]
i+=1
k+=1
else:
list1[k] = right_list[j]
j+=1
k+=1
while i < len(left_list): # I did this as for the end condition of above loop as when i or j will be equal to len(left/right list)
list1[k] = left_list[i]
i+=1
k+=1
while j < len(right_list):
list1[k] = right_list[j]
j+=1
k+=1
#Start watching from here and then as when function call will come then go check function
n = int(input("Enter how many element you want in the list : "))
list1 = [int(input()) for i in range(n)]
mergesort(list1)
print("sorted list : " + str(list1))