Program to bubble sort LinkedList

 In this program we will see the bubble sort algorithm to sort Linked List







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

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

    def display(self):
        temp = self.head
        while temp!=None:
            print(temp.data,end="=>")
            temp = temp.next
    def length(self):
        temp = self.head
        count = 0
        while temp!=None:
            count = count+1
            temp = temp.next
        return count
    def sort(self):
        temp = self.head
        count = 0
        while count<self.length():
            temp1 = temp
            while temp1.next!=None:
                if temp1.next.data<temp1.data:
                    hold = temp1.next.data
                    temp1.next.data = temp1.data
                    temp1.data = hold
                    temp1 = temp1.next
                else:
                    temp1 = temp1.next
            count = count+1


if __name__ == "__main__":
    llist = LinkedList()
    first = Node(50)
    second = Node(40)
    third = Node(30)
    fourth = Node(30)
    fifth = Node(10)
    llist.head = first
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = fifth
    llist.display()
    llist.sort()
    print("\nAfter sorting")
    llist.display()

No comments:

Post a Comment