Bubble Sort On Doubly Linked List | structure of a node ; Function to insert a node at the beginning of a linked list ; Function to print nodes in a given linked list ; Bubble sort the given linked list ; Checking for empty list ; Driver code ; start with empty linked list ; Create linked list from the array arr [ ] . Created linked list will be 1.11 . 2.56 . 12 ; print list before sorting ; sort the linked list ; print list after sorting
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def insertAtTheBegin ( start_ref , data ) : NEW_LINE INDENT ptr1 = Node ( data ) NEW_LINE ptr1 . data = data ; NEW_LINE ptr1 . next = start_ref ; NEW_LINE if ( start_ref != None ) : NEW_LINE ( start_ref ) . prev = ptr1 ; NEW_LINE start_ref = ptr1 ; NEW_LINE return start_ref NEW_LINE DEDENT def printList ( start ) : NEW_LINE INDENT temp = start ; NEW_LINE print ( ) NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = ' ▁ ' ) NEW_LINE temp = temp . next ; NEW_LINE DEDENT DEDENT def bubbleSort ( start ) : NEW_LINE INDENT swapped = 0 NEW_LINE lptr = None ; NEW_LINE if ( start == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT while True : NEW_LINE INDENT swapped = 0 ; NEW_LINE ptr1 = start ; NEW_LINE while ( ptr1 . next != lptr ) : NEW_LINE INDENT if ( ptr1 . data > ptr1 . next . data ) : NEW_LINE INDENT ptr1 . data , ptr1 . next . data = ptr1 . next . data , ptr1 . data NEW_LINE swapped = 1 ; NEW_LINE DEDENT ptr1 = ptr1 . next ; NEW_LINE DEDENT lptr = ptr1 ; NEW_LINE if swapped == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 56 , 2 , 11 , 1 , 90 ] NEW_LINE start = None ; NEW_LINE for i in range ( 6 ) : NEW_LINE INDENT start = insertAtTheBegin ( start , arr [ i ] ) ; NEW_LINE DEDENT print ( " Linked ▁ list ▁ before ▁ sorting ▁ " , end = ' ' ) ; NEW_LINE printList ( start ) ; NEW_LINE bubbleSort ( start ) ; NEW_LINE print ( " Linked list after sorting   " , end = ' ' ) ; NEW_LINE printList ( start ) ; NEW_LINE DEDENT