m2skills

merge sort python

Sep 28th, 2017
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.85 KB | None | 0 0
  1. # program to implement merger sort recursive in python
  2.  
  3. # function that sorts and merges the list
  4. def Merge(data, left, middle, right):
  5.    
  6.     # print("Before merge")
  7.     # print(data)
  8.    
  9.     # storing the left and the right list length
  10.     leftLength = middle - left + 1
  11.     rightLength = right - middle
  12.  
  13.     # creating 2 dummy lists to hold the split lists
  14.     leftTemp  = []
  15.     rightTemp = []
  16.  
  17.     for i in range(leftLength):
  18.         leftTemp.append(data[left + i])
  19.  
  20.     for i in range(rightLength):
  21.         rightTemp.append(data[middle + 1 + i])
  22.  
  23.     # sorting and merging the left and right lists by element wise comparison
  24.     i = 0
  25.     j = 0
  26.     k = left
  27.  
  28.     while i < leftLength and j < rightLength:
  29.         if leftTemp[i] <= rightTemp[j]:
  30.             data[k] = leftTemp[i]
  31.             i += 1
  32.         else:
  33.             data[k] = rightTemp[j]
  34.             j += 1
  35.         k += 1
  36.  
  37.     while i < leftLength:
  38.         data[k] = leftTemp[i]
  39.         i += 1
  40.         k += 1
  41.  
  42.     while j < rightLength:
  43.         data[k] = rightTemp[j]
  44.         j += 1
  45.         k += 1
  46.    
  47.     # print("After Merge")
  48.     #print(left, right, data)
  49.     leftTemp.clear()
  50.     rightTemp.clear()
  51.  
  52.    
  53. # recursive merge sort function
  54. def MergeSortRecursive(data, left, right):
  55.     # keep making the recursive calls till the splited list has only one element
  56.     if left < right:
  57.         # calculate middle element
  58.         middle = left + int((right - left) / 2)
  59.        
  60.         # pass the left half and right half to recursive calls
  61.         MergeSortRecursive(data, left, middle)
  62.         MergeSortRecursive(data, middle + 1, right)
  63.        
  64.         # finally start sorting and merging the lists
  65.         Merge(data, left, middle, right)
  66.        
  67.     return data
  68.  
  69.  
  70. print("Program to implement Recursive Merge sort algorithm in python")
  71. myList = list(map(int, input("\nEnter the elements to sorted as spaced integers : ").strip().split()))
  72. print("The list before sorting is : ")
  73. print(myList)
  74. myList = MergeSortRecursive(myList, 0, len(myList)-1)
  75. print("\nThe sorted list is : ")
  76. print(myList)
Add Comment
Please, Sign In to add comment