MCPcopy Create free account
hub / github.com/geekcomputers/Python / LinkedList

Class LinkedList

Sorting Algorithims/heapsort_linkedlist.py:7–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5
6
7class LinkedList:
8 def __init__(self):
9 self.head = None
10
11 def push(self, data):
12 new_node = Node(data)
13 new_node.next = self.head
14 self.head = new_node
15
16 def print_list(self):
17 current = self.head
18 while current:
19 print(current.data, end=" -> ")
20 current = current.next
21 print("None")
22
23 def heapify(self, n, i):
24 largest = i
25 left = 2 * i + 1
26 right = 2 * i + 2
27
28 current = self.head
29 for _ in range(i):
30 current = current.next
31
32 if left < n and current.data < current.next.data:
33 largest = left
34
35 if right < n and current.data < current.next.data:
36 largest = right
37
38 if largest != i:
39 self.swap(i, largest)
40 self.heapify(n, largest)
41
42 def swap(self, i, j):
43 current_i = self.head
44 current_j = self.head
45
46 for _ in range(i):
47 current_i = current_i.next
48
49 for _ in range(j):
50 current_j = current_j.next
51
52 current_i.data, current_j.data = current_j.data, current_i.data
53
54 def heap_sort(self):
55 n = 0
56 current = self.head
57 while current:
58 n += 1
59 current = current.next
60
61 for i in range(n // 2 - 1, -1, -1):
62 self.heapify(n, i)
63
64 for i in range(n - 1, 0, -1):

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected