Skip to content

Commit b346fce

Browse files
authored
Merge pull request larissalages#157 from sel3ne/master
fixed heapSort and implented unitest
2 parents 67797f2 + 2c60393 commit b346fce

File tree

2 files changed

+46
-8
lines changed

2 files changed

+46
-8
lines changed

classical_algorithms/python/Heap Sort.py renamed to classical_algorithms/python/heapsort.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,30 @@ def heapify(arr, n, i):
2323
def heapSort(arr):
2424
n = len(arr)
2525

26+
# empty list returns sorted empty list
27+
if n == 0:
28+
return []
29+
30+
# list of size one, returns same list
31+
if n == 1:
32+
return arr
33+
2634
# Build a maxheap.
2735
for i in range(n//2 - 1, -1, -1):
2836
heapify(arr, n, i)
2937

3038
# One by one extract elements
3139
for i in range(n-1, 0, -1):
3240
arr[i], arr[0] = arr[0], arr[i] # swap
33-
heapify(arr, i, 0)
34-
35-
print('Enter a list of numbers')
36-
arr = list(map(int,input().split()))
37-
heapSort(arr)
38-
print('After performing heap sort')
39-
for i in arr:
40-
print(i,end =' ')
41+
heapify(arr, i, 0)
42+
return arr
43+
44+
45+
# not execute the code when imported
46+
if __name__ == "__main__":
47+
print('Enter a list of numbers')
48+
arr = list(map(int,input().split()))
49+
heapSort(arr)
50+
print('After performing heap sort')
51+
for i in arr:
52+
print(i,end =' ')
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import unittest
2+
from classical_algorithms.python.heapsort import heapSort
3+
4+
class TestHeapSort(unittest.TestCase):
5+
def test_heap_sort(self):
6+
7+
print('None Input')
8+
self.assertRaises(TypeError, heapSort, None)
9+
10+
print('Empty Input')
11+
self.assertEqual(heapSort([]), [])
12+
13+
print('One Element')
14+
self.assertEqual(heapSort([13]), [13])
15+
16+
print('Multipe nElements')
17+
test_array = [-23,-1,0,1,10,-10,1000, 2]
18+
solution_array = [-23,-10,-1,0,1,2,10,1000]
19+
20+
self.assertEqual(heapSort(test_array), solution_array)
21+
22+
print('Successful test_heap_sort\n')
23+
24+
25+
if __name__=='__main__':
26+
unittest.main()

0 commit comments

Comments
 (0)