Bubble Sort On Doubly Linked List | C # program to sort a doubly linked list using bubble sort ; 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
using System ; class GFG { public class Node { public int data ; public Node prev ; public Node next ; } ; static Node insertAtTheBegin ( Node start_ref , int data ) { Node ptr1 = new Node ( ) ; ptr1 . data = data ; ptr1 . next = start_ref ; if ( start_ref != null ) ( start_ref ) . prev = ptr1 ; start_ref = ptr1 ; return start_ref ; } static void printList ( Node start ) { Node temp = start ; Console . WriteLine ( ) ; while ( temp != null ) { Console . Write ( temp . data + " ▁ " ) ; temp = temp . next ; } } static Node bubbleSort ( Node start ) { int swapped ; Node ptr1 ; Node lptr = null ; if ( start == null ) return null ; do { swapped = 0 ; ptr1 = start ; while ( ptr1 . next != lptr ) { if ( ptr1 . data > ptr1 . next . data ) { int t = ptr1 . data ; ptr1 . data = ptr1 . next . data ; ptr1 . next . data = t ; swapped = 1 ; } ptr1 = ptr1 . next ; } lptr = ptr1 ; } while ( swapped != 0 ) ; return start ; } public static void Main ( String [ ] args ) { int [ ] arr = { 12 , 56 , 2 , 11 , 1 , 90 } ; int i ; Node start = null ; for ( i = 0 ; i < 6 ; i ++ ) start = insertAtTheBegin ( start , arr [ i ] ) ; Console . Write ( " STRNEWLINE ▁ Linked ▁ list ▁ before ▁ sorting ▁ " ) ; printList ( start ) ; start = bubbleSort ( start ) ; Console . Write ( " STRNEWLINE ▁ Linked ▁ list ▁ after ▁ sorting ▁ " ) ; printList ( start ) ; } }