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

Products Which I like

Induction Buy now Induction Buy now

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

Instagram OSINT

 OSINT stands for Open Source INTelligence . it means any information that can legally gathered from free , open source software or tool. if you want simple Example of OSINT then any search engine is OSINT. Today's Topic is Instagram OSINT then let's get started......