From 238909730dc5d2d7dad5430c2dcc0da10adede8a Mon Sep 17 00:00:00 2001 From: nryoung Date: Tue, 28 Aug 2012 11:35:22 -0600 Subject: [PATCH] Added skeleton code for heap sort --- algorithms/sorting/heap_sort.py | 43 ++++++++++++++++++++++++++++++++ algorithms/tests/test_sorting.py | 15 +++++++++-- requirements.txt | 4 +++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 algorithms/sorting/heap_sort.py create mode 100644 requirements.txt diff --git a/algorithms/sorting/heap_sort.py b/algorithms/sorting/heap_sort.py new file mode 100644 index 0000000..968605f --- /dev/null +++ b/algorithms/sorting/heap_sort.py @@ -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 diff --git a/algorithms/tests/test_sorting.py b/algorithms/tests/test_sorting.py index 61d89c9..b9e747c 100644 --- a/algorithms/tests/test_sorting.py +++ b/algorithms/tests/test_sorting.py @@ -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): """ @@ -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): @@ -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) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..65d9a46 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +argparse==1.2.1 +distribute==0.6.27 +nose==1.1.2 +wsgiref==0.1.2