Skip to main content

Bubble sort for Singly Linked List Using Python

 When It's comes to sorting Linked list , it is not preferred to use Bubble sort, Because it is too Slow. but just for learning purpose we will take a look on Bubble Sort.

First You should check out Singly Linked List in Python for basic knowledge of linked list.

Now Let's Begin..

So as we know Bubble sort works by swapping elements.

  • Creating Node Class:

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


  • Bubble sort:

class LinkedList:
def __init__(self):
self.head = None 
 
""" Bubble Sort"""
def bubbleSort(self):
cur = self.head
# print("head: ",self.head.data)
idx = None
if self.head == None:
return
else:
#this while loop won't stop until cur = None (last element)
while cur:
# taking next element in idx
idx = cur.next
# this while loop won't stop until idx = None
while idx:
# swap
if cur.data > idx.data:
cur.data, idx.data = idx.data, cur.data
idx = idx.next

cur = cur.next
  

Time Complexity: 

  • Best : Ω(n)
  • Average: Θ(n*n)
  • Worst: O(n*n)

Note: If you want to share your suggestion You can share in comments section,          Open for suggestion.

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