Skip to content

Commit

Permalink
Merge pull request #31 from vishal-wadhwa/heap-sort/issue-#2
Browse files Browse the repository at this point in the history
added heap-sort as a part of array sorting
  • Loading branch information
ionicc authored Oct 4, 2018
2 parents e7bd769 + 2405ad2 commit 33a7e6e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Arrays-Sorting/src/Heap_Sort/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.vscode
*.pyc
env
39 changes: 39 additions & 0 deletions Arrays-Sorting/src/Heap_Sort/heap_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
def heapify(arr, n, i):
largest = i
l = 2 *i + 1
r = 2 *i + 2

if l < n and arr[l] > arr[largest]:
largest = l

if r < n and arr[r] > arr[largest]:
largest = r

if largest != i:
arr[largest], arr[i] = arr[i], arr[largest]
heapify(arr, n, largest)


def build_heap(arr):
arr_len = len(arr)
for i in range(arr_len//2 - 1, -1, -1):
heapify(arr, arr_len, i)


def heap_sort(arr):
build_heap(arr)
for i in range(len(arr) - 1, -1, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)


def main():
arr = [9.7, 1.3, -2, 1, 0]
print("Before: ", arr)
heap_sort(arr)
assert arr == [-2, 0, 1, 1.3, 9.7]
print("After: ", arr)


if __name__ == '__main__':
main()

0 comments on commit 33a7e6e

Please sign in to comment.