Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to implement merger sort recursive in python
- # function that sorts and merges the list
- def Merge(data, left, middle, right):
- # print("Before merge")
- # print(data)
- # storing the left and the right list length
- leftLength = middle - left + 1
- rightLength = right - middle
- # creating 2 dummy lists to hold the split lists
- leftTemp = []
- rightTemp = []
- for i in range(leftLength):
- leftTemp.append(data[left + i])
- for i in range(rightLength):
- rightTemp.append(data[middle + 1 + i])
- # sorting and merging the left and right lists by element wise comparison
- i = 0
- j = 0
- k = left
- while i < leftLength and j < rightLength:
- if leftTemp[i] <= rightTemp[j]:
- data[k] = leftTemp[i]
- i += 1
- else:
- data[k] = rightTemp[j]
- j += 1
- k += 1
- while i < leftLength:
- data[k] = leftTemp[i]
- i += 1
- k += 1
- while j < rightLength:
- data[k] = rightTemp[j]
- j += 1
- k += 1
- # print("After Merge")
- #print(left, right, data)
- leftTemp.clear()
- rightTemp.clear()
- # recursive merge sort function
- def MergeSortRecursive(data, left, right):
- # keep making the recursive calls till the splited list has only one element
- if left < right:
- # calculate middle element
- middle = left + int((right - left) / 2)
- # pass the left half and right half to recursive calls
- MergeSortRecursive(data, left, middle)
- MergeSortRecursive(data, middle + 1, right)
- # finally start sorting and merging the lists
- Merge(data, left, middle, right)
- return data
- print("Program to implement Recursive Merge sort algorithm in python")
- myList = list(map(int, input("\nEnter the elements to sorted as spaced integers : ").strip().split()))
- print("The list before sorting is : ")
- print(myList)
- myList = MergeSortRecursive(myList, 0, len(myList)-1)
- print("\nThe sorted list is : ")
- print(myList)
Add Comment
Please, Sign In to add comment