Skip to content

Instantly share code, notes, and snippets.

@dnozay
Last active October 24, 2017 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnozay/35ce05cd0d618c81c4c4ef82f285fdcb to your computer and use it in GitHub Desktop.
Save dnozay/35ce05cd0d618c81c4c4ef82f285fdcb to your computer and use it in GitHub Desktop.
min-heap, max-heap, heapsort
"""
Quick and dirty min-heap, max-heap and heapsort implementations.
"""
from typing import Any, List
def _parent(i:int):
return (i - 1) >> 1
def _left(i:int):
return (i << 1) + 1
def _right(i:int):
return (i + 1) << 1
def build_max_heap(A:List):
n = len(A)
# in-place in O(n) time.
# we start from the bottom and up, bottom layer has has n//2 1-element heaps.
for i in range(n//2 - 1, -1, -1): # reversed(range(n//2))
max_heapify(A, i, n)
def build_min_heap(A:List):
n = len(A)
for i in range(n//2 - 1, -1, -1): # reversed(range(n//2))
min_heapify(A, i, n)
def max_heapify(A:List, i:int, n:int):
# precondition: left and right are already max-heaps.
# parent (i pos) is inserted and we need to restore heap condition.
# n = len(A)
l = _left(i)
r = _right(i)
if l < n and A[l] > A[i]:
largest = l
else:
largest = i
if r < n and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, largest, n)
def min_heapify(A:List, i:int, n:int):
# precondition: left and right are already min-heaps.
# parent (i pos) is inserted and we need to restore heap condition.
# n = len(A)
l = _left(i)
r = _right(i)
if l < n and A[l] < A[i]:
smallest = l
else:
smallest = i
if r < n and A[r] < A[smallest]:
smallest = r
if smallest != i:
A[i], A[smallest] = A[smallest], A[i]
min_heapify(A, smallest, n)
def max_heap_insert(A:List, item:Any):
i = len(A)
A.append(item) # inserted at pos = i.
while i > 0:
p = _parent(i)
if A[p] < A[i]:
A[i], A[p] = A[p], A[i]
i = p
else:
break
def min_heap_insert(A:List, item:Any):
i = len(A)
A.append(item) # inserted at pos = i.
while i > 0:
p = _parent(i)
if A[i] < A[p]:
A[i], A[p] = A[p], A[i]
i = p
else:
break
def max_heap_pop(A:List) -> Any:
n = len(A)
assert n, 'no elements'
top, A[0] = A[0], A[n-1]
A.pop()
max_heapify(A, 0, n-1)
return top
def min_heap_pop(A:List) -> Any:
n = len(A)
assert n, 'no elements'
top, A[0] = A[0], A[n-1]
A.pop()
min_heapify(A, 0, n-1)
return top
def heapsort(A:List, reverse:bool=False):
build, heapify = (build_min_heap, min_heapify) if reverse else (build_max_heap, max_heapify)
n = len(A)
build(A)
for i in range(n - 1, 0, -1):
A[0], A[i] = A[i], A[0]
heapify(A, 0, i)
Copyright 2017 Damien Nozay
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from random import shuffle
import pytest
def test_access():
# 0
# 1 2
# 3 4 5 6
assert _parent(1) == 0
assert _parent(2) == 0
assert _left(0) == 1
assert _right(0) == 2
assert _left(1) == 3
assert _right(2) == 6
def test_max_heapify():
A = []
max_heapify(A, 0, len(A))
assert A == []
# 1 3
# 2 3 -> 2 6
# 4 5 6 x 4 5 1 x
A = [1, 2, 3, 4, 5, 6]
max_heapify(A, 0, len(A))
assert A == [3, 2, 6, 4, 5, 1]
def test_build_max_heap():
A = []
build_max_heap(A)
assert A == []
# 1 6
# 2 3 -> 5 3
# 4 5 6 x 4 2 1 x
A = [1, 2, 3, 4, 5, 6]
build_max_heap(A)
assert A == [6, 5, 3, 4, 2, 1]
def test_heapsort():
A = list(range(100))
shuffle(A)
heapsort(A)
assert list(A) == list(range(100))
heapsort(A, reverse=True)
assert list(A) == list(reversed(range(100)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment