Skip to content

Commit b03d480

Browse files
authored
Create heapsort_linkedlist.py
1 parent 76725dc commit b03d480

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
6+
class LinkedList:
7+
def __init__(self):
8+
self.head = None
9+
10+
def push(self, data):
11+
new_node = Node(data)
12+
new_node.next = self.head
13+
self.head = new_node
14+
15+
def print_list(self):
16+
current = self.head
17+
while current:
18+
print(current.data, end=" -> ")
19+
current = current.next
20+
print("None")
21+
22+
def heapify(self, n, i):
23+
largest = i
24+
left = 2 * i + 1
25+
right = 2 * i + 2
26+
27+
current = self.head
28+
for _ in range(i):
29+
current = current.next
30+
31+
if left < n and current.data < current.next.data:
32+
largest = left
33+
34+
if right < n and current.data < current.next.data:
35+
largest = right
36+
37+
if largest != i:
38+
self.swap(i, largest)
39+
self.heapify(n, largest)
40+
41+
def swap(self, i, j):
42+
current_i = self.head
43+
current_j = self.head
44+
45+
for _ in range(i):
46+
current_i = current_i.next
47+
48+
for _ in range(j):
49+
current_j = current_j.next
50+
51+
current_i.data, current_j.data = current_j.data, current_i.data
52+
53+
def heap_sort(self):
54+
n = 0
55+
current = self.head
56+
while current:
57+
n += 1
58+
current = current.next
59+
60+
for i in range(n // 2 - 1, -1, -1):
61+
self.heapify(n, i)
62+
63+
for i in range(n - 1, 0, -1):
64+
self.swap(0, i)
65+
self.heapify(i, 0)
66+
67+
# Example usage:
68+
linked_list = LinkedList()
69+
linked_list.push(12)
70+
linked_list.push(11)
71+
linked_list.push(13)
72+
linked_list.push(5)
73+
linked_list.push(6)
74+
linked_list.push(7)
75+
76+
print("Original Linked List:")
77+
linked_list.print_list()
78+
79+
linked_list.heap_sort()
80+
81+
print("Sorted Linked List:")
82+
linked_list.print_list()

0 commit comments

Comments
 (0)