Skip to content

Commit

Permalink
Added skeleton code for heap sort
Browse files Browse the repository at this point in the history
  • Loading branch information
nryoung committed Aug 28, 2012
1 parent 3f0c20a commit 2389097
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
43 changes: 43 additions & 0 deletions algorithms/sorting/heap_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
""" Implementation of Heap Sort """

def parent(i):
return i/2

def left(i):
return 2*i

def right(i):
return 2*i+1

def max_heapify(seq, i, n):
l = left(i)
r = right(i)

if l <= n and seq[n] > seq[i]:
largest = l
else:
largest = i
if r <= n and seq[r] > seq[largest]:
largest = r

if largest != i:
seq[i], seq[largest] = seq[largest], seq[i]
max_heapify(seq, largest, n)

def heap_length(seq):
return len(seq) - 1

def build_heap(seq):
n = heap_length(seq)
for i in range(n/2,0,-1):
max_heapify(seq, i, n)

def sort(seq):
build_heap(seq)
heap_size = heap_length(seq)
for i in range(heap_size,1,-1):
seq[1], seq[i] = seq[i], seq[1]
heap_size = heap_size - 1
max_heapify(seq, 1, heap_size)

return seq
15 changes: 13 additions & 2 deletions algorithms/tests/test_sorting.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import random
import unittest
from ..sorting import bubble_sort, selection_sort, insertion_sort, merge_sort, quick_sort
from ..sorting import bubble_sort, selection_sort, insertion_sort, merge_sort, quick_sort, heap_sort

class TestBubbleSort(unittest.TestCase):
"""
Expand Down Expand Up @@ -57,7 +57,6 @@ def test_merge(self):
class TestQuickSort(unittest.TestCase):
"""
Test Quick sort on a small range from 0-9
also tests partition function included in quick sort.
"""

def test_quicksort(self):
Expand All @@ -66,3 +65,15 @@ def test_quicksort(self):
self.seq = quick_sort.sort(self.seq)
self.assertIs(self.seq[0], 0)
self.assertIs(self.seq[-1], 9)

class TestHeapSort(unittest.TestCase):
"""
Test Heap sort on a small range from 0-9
"""

def test_heapsort(self):
self.seq = range(10)
random.shuffle(self.seq)
self.seq = heap_sort.sort(self.seq)
self.assertIs(self.seq[0], 0)
self.assertIs(self.seq[-1], 9)
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
argparse==1.2.1
distribute==0.6.27
nose==1.1.2
wsgiref==0.1.2

0 comments on commit 2389097

Please sign in to comment.