Skip to content

Commit 7b9fa9e

Browse files
committed
[Feature] Added heapsort with heapq built-in and with custom heap.
1 parent 80cbc31 commit 7b9fa9e

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ $ coverage report -m
2727
* [Quicksort](sorts/quicksort.py)
2828
* [Mergesort](sorts/mergesort.py)
2929
* [Radixsort](sorts/radixsort.py)
30+
* [Heapsort](sorts/heapsort.py)
3031

3132
### Searching Algorithms
3233
* [BinarySearch](searches/binary_search.py)

sorts/heapsort.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from copy import deepcopy
2+
from heapq import heapify, heappop
3+
from structures.heap import Heap
4+
5+
def heap_sort(lst:list):
6+
copy_list = deepcopy(lst)
7+
heapify(copy_list)
8+
return [heappop(copy_list) for i in range(len(copy_list))]
9+
10+
def max_heap_sort(lst:list):
11+
copy_list = deepcopy(lst)
12+
# make all elements negative, so heap is a max heap
13+
copy_list = list(map(lambda x: x * -1, copy_list))
14+
heapify(copy_list)
15+
copy_list = [heappop(copy_list) for i in range(len(copy_list))]
16+
copy_list = list(map(lambda x: x * -1, copy_list))
17+
return copy_list
18+
19+
def custom_heap_sort(lst:list,sort='min'):
20+
copy_list = deepcopy(lst)
21+
if sort == 'max':
22+
copy_list = list(map(lambda x: x * -1, copy_list))
23+
heap = Heap()
24+
heap.build(copy_list)
25+
sorted_list = [heap.delete_min() for i in range(heap.size())]
26+
if sort == 'max':
27+
sorted_list = list(map(lambda x: x * -1, sorted_list))
28+
return sorted_list

tests/test_heap_sort.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import unittest
2+
from sorts.heapsort import heap_sort, max_heap_sort, custom_heap_sort
3+
4+
class TestHeapSort(unittest.TestCase):
5+
6+
random_list = [7, 9, 3, 24, 84, 12, 3, 4, 20, 39, 8, 2, 4, 99, 24, 4]
7+
8+
sorted_list = [2, 3, 3, 4, 4, 4, 7, 8, 9, 12, 20, 24, 24, 39, 84, 99]
9+
10+
def test_heap_sort(self):
11+
self.assertEqual(self.sorted_list, heap_sort(self.random_list))
12+
13+
def test_max_heap_sort(self):
14+
self.assertEqual(self.sorted_list[::-1], max_heap_sort(self.random_list))
15+
16+
def test_heap_sort_custom(self):
17+
self.assertEqual(self.sorted_list, custom_heap_sort(self.random_list))
18+
19+
def test_heap_max_sort_custom(self):
20+
self.assertEqual(self.sorted_list[::-1], custom_heap_sort(self.random_list, 'max'))

0 commit comments

Comments
 (0)