Skip to main content

Merge sort for Singly Linked List using Python

 Merge Sort , so merge sort divide linked list into smaller part and sort and merge those parts in one linked list, let's see how?

 First Check out Basic Operation on Singly Linked list. 

Code:

class Node:
def __init__(self, data=None):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

""" Merge Sort"""
# this funtion sort divided linked list and merge
# them into one linked list
def sortedMerge(self,a,b):
result = None
if a is None:
return b
if b is None:
return a

if a.data <= b.data:
result = a
result.next = self.sortedMerge(a.next,b)
else:
result = b
result.next = self.sortedMerge(a,b.next)

return result

def mergeSort(self,h):
#base case
if h is None or h.next is None:
return h
#find middle
middle = self.getMiddle(h)
# take middle.next in nextToMiddle for dividing
# linked list in two part
nextToMiddle = middle.next
# it divides
middle.next = None
# recursion
left = self.mergeSort(h)
right = self.mergeSort(nextToMiddle)
#it stops when linked list won't divided

#now sort and merge
sortedList = self.sortedMerge(left,right)
return sortedList

# it will find middle of linked list
def getMiddle(self,head):
if head is None:
return head
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow

 Time Complexity:

  • Best: 𝛺(n*log n)
  • Average:Θ(n*log n)
  • Worst: O(n*log n)
 Space Complexity: O(log n)

Note: if You have any suggestion put in comments.

Thank You 😊😊

Other Sorting Algorithms:

 


Comments

Popular posts from this blog

Products Which I like

Induction Buy now Induction Buy now

Pascal's Triangle

 Pascal's Triangle Introduction In mathematics, Pascal’s triangle is triangular array of binomial coefficient. below you can see how it looks like… 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 How to Build it? First of all start with “1” and second rows as “1 1” then we can clearly see every element in next rows(except 1) if sum of two elements from above row. (i.e, 1+1=2, 1+2=3, 1+3=4) and with this rules we can create pascal’s triangle of n rows. Below is visual of how it will look like, Formula let’s take 0th row as first row and 0th column as first column, so we can get each value using formula where n is row number and k is column number. so for finding 1st(0 indexed) element in 2nd row we can write 2C1 which will give 2. There is one another technique, in which we need to solve (x + y)^n for nth row, if we solve (x +y)² then we will get 2nd row as coefficient of x and y in this solved formula which is x² + 2xy + y² . coefficients are (...

Add BUY ME A COFFEE To Your Github/Website

 Hey Everyone , Today we'll discuss how to add buy me a coffee to your github or website. so let's begin