Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Heapsort implementation #93

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions SortingAlgorithms/heap_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Heap:
def __init__(self, right, numbers):
self.right = right
self.numbers = numbers
self.build_heap()

def build_heap(self):
for i in range(self.right // 2 - 1, -1, -1):
self.heapify(i, self.right)

def heapify(self, start, heap_size):
while True:
left = 2 * start + 1
right = 2 * start + 2
max = start
if left < heap_size and self.numbers[left] > self.numbers[max]:
max = left
if right < heap_size and self.numbers[right] > self.numbers[max]:
max = right
if max == start:
return
self._swap(max, start)
start = max

def remove_max(self):
self.right -= 1
self._swap(0, self.right)
self.heapify(0, self.right)

def _swap(self, i, j):
self.numbers[i], self.numbers[j] = self.numbers[j], self.numbers[i]


def heap_sort(values):
heap = Heap(len(values), values)
for i in range(len(values) - 1, 0, -1):
heap.remove_max()