Bubble sort on linked list in python

Python program for Bubble sort on linked list. Here more solutions.
# Python 3 program for
# Bubble Sort For Linked List
class Node :
data = 0
next = None
def __init__(self, data) :
self.data = data
self.next = None
class LinkedList :
head = None
# Class constructors
def __init__(self) :
self.head = None
# Add node at the beginning of linked list
def insert(self, value) :
# Create a new node
node = Node(value)
# Add node at front
node.next = self.head
# Make new head
self.head = node
# Display all elements
def display(self) :
if (self.head != None) :
temp = self.head
while (temp != None) :
# Display node value
print(" " + str(temp.data), end ="")
# Visit to next node
temp = temp.next
else :
print("Empty Linked list")
# Perform bubble sort in single linked list
def bubbleSort(self) :
if (self.head != None) :
current = None
status = False
while True :
# Start with first node
current = self.head
# Reset working status
status = False
while (current != None and current.next != None) :
if (current.data > current.next.data) :
# Swap node values
current.data = current.data + current.next.data
current.next.data = current.data - current.next.data
current.data = current.data - current.next.data
# When node value change
status = True
# Visit to next node
current = current.next
if((status) == False) :
break
else :
print("Empty Linked list")
@staticmethod
def main() :
task = LinkedList()
# Insert element of linked list
task.insert(15)
task.insert(5)
task.insert(42)
task.insert(9)
task.insert(50)
task.insert(7)
print(" Before sort : ", end ="")
# Display all node
task.display()
task.bubbleSort()
print("\n After sort : ", end ="")
task.display()
if __name__=="__main__":
LinkedList.main()
Output
Before sort : 7 50 9 42 5 15
After sort : 5 7 9 15 42 50
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment