[Python] Bubble sort on Doubly Linked List not working

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I have been doing DSA lately on python, this time tried bubble-sort algorithm on a doubly linked list.

    Unfortunately, the method is not giving proper result.

    Please correct me, tell me where I am going wrong (I tried a lot but couldn't understand). Please explain and suggest the required changes.

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


    class DoublyLinkedList:
    def __init__(self):
    self.head = None
    self.tail = None
    self.next = None
    self.prev = None
    self.count = 0


    def bubble_sort(self):
    if self.head is None:
    return f"Linked list is empty!"
    elif self.head.next is None:
    return self.head
    else:
    left = self.head
    right = self.head.next
    while True:
    flag = 'sorted'
    while True:
    if right is None:
    break
    if left.value > right.value:
    flag = 'unsorted'
    if (left == self.head) and (right == self.tail): #only two nodes
    self.tail = left
    self.head = right
    elif left == self.head: #edge case of left
    self.head = right
    elif right == self.tail: #edge case of right
    self.tail = left
    temp_right = right.next
    temp_left = left.prev
    left.next = temp_right
    left.prev = right
    right.next = left
    right.prev = temp_left
    right = left.next
    else:
    left = left.next
    right = right.next
    left = self.head
    right = self.head.next
    if flag == 'sorted':
    return self


    Please help!

    Continue reading...

Compartilhe esta Página