Posts

Showing posts with the label Bubble sort

Sorting singly linked list with bubble sort

 Sorting a singly linked list using the bubble sort algorithm involves repeatedly traversing the list and swapping adjacent elements if they are in the wrong order. Here's an example of how you can implement bubble sort for a singly linked list in a hypothetical programming language: ```python class Node:     def __init__(self, data):         self.data = data         self.next = None def bubble_sort_linked_list(head):     if head is None:         return None     # Flag to check if any swaps were made in the pass     swapped = True     while swapped:         swapped = False         current = head         prev = None         while current and current.next:             if current.data > current.next.data:                 # Swap the nodes                 if prev is not None:                     prev.next = current.next                 else:                     head = current.next                 current.next, current.next.next = current.next.next, current                 prev = curr