Skip to main content

Insertion Sort for Singly LInked List Using Python

Let's see How Insertion sort work on linked list.

In This Post we're gonna talk about Insertion Sort for singly linked list.

First Check out Basic Operation on Singly Linked list.

Code:

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

""" Insertion Sort"""
def insertionSort(self,head_ref):
sortedLL = None # sorted linked list for entering data in from main linked list
cur = head_ref
while cur:
nxt = cur.next # take cur.next in nxt bcz sortedInsert will overwrite cur
sortedLL = self.sortedInsert(sortedLL, cur)
cur = nxt
head_ref = sortedLL
return head_ref

def sortedInsert(self,head_ref, NewNode):
if head_ref is None or head_ref.data > NewNode.data:
NewNode.next = head_ref
head_ref = NewNode
else:
cur = head_ref
while cur.next != None and cur.next.data < NewNode.data:
cur = cur.next
NewNode.next = cur.next
cur.next = NewNode
return head_ref

Time Complexity:

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

Note: if You have any suggestion put in comments.

Thank You 😊😊

Other Sorting Algorithms:

 


Comments

Popular posts from this blog

Makefile

 You may have seen file named Makefile or you may have type command like make, make install. so what is this file Makefile and what are this command. let's discuss about it.

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 (...