From 04d15692a8dfb679de7bf06bdc02426fec54adf3 Mon Sep 17 00:00:00 2001 From: arijit pande Date: Sun, 14 Aug 2016 09:51:52 +0000 Subject: [PATCH 1/2] added implementation for heap sort algorithm --- sorts/heap_sort.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 sorts/heap_sort.py diff --git a/sorts/heap_sort.py b/sorts/heap_sort.py new file mode 100644 index 000000000..e5ed488b2 --- /dev/null +++ b/sorts/heap_sort.py @@ -0,0 +1,35 @@ +def heapify(unsorted,index,heap_size): + largest = index + left_index = 2*index + 1 + right_index = 2*index + 2 + if left_index < heap_size and unsorted[left_index] > unsorted[largest]: + largest = left_index + + if right_index < heap_size and unsorted[right_index] > unsorted[largest]: + largest = right_index + + if largest != index: + unsorted[largest],unsorted[index] = unsorted[index],unsorted[largest] + heapify(unsorted,largest,heap_size) + +def heap_sort(unsorted): + n=len(unsorted) + for i in range (n/2 - 1 , -1, -1) : + heapify(unsorted,i,n) + for i in range(n - 1, -1, -1): + unsorted[0], unsorted[i] = unsorted[i], unsorted[0] + heapify(unsorted,0,i) + return unsorted + + +if __name__ == '__main__': + import sys + if sys.version_info.major < 3: + input_function = raw_input + else: + input_function = input + + user_input = input_function('Enter numbers separated by coma:\n') + unsorted = [int(item) for item in user_input.split(',')] + print heap_sort(unsorted) + From 7ce559ecdd3e4430baa9e8e42f754f182826a22e Mon Sep 17 00:00:00 2001 From: arijit pande Date: Sun, 14 Aug 2016 10:04:21 +0000 Subject: [PATCH 2/2] added __future__ module --- sorts/heap_sort.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sorts/heap_sort.py b/sorts/heap_sort.py index e5ed488b2..5d1cbbbd0 100644 --- a/sorts/heap_sort.py +++ b/sorts/heap_sort.py @@ -1,3 +1,7 @@ + +from __future__ import print_function + + def heapify(unsorted,index,heap_size): largest = index left_index = 2*index + 1 @@ -31,5 +35,5 @@ if __name__ == '__main__': user_input = input_function('Enter numbers separated by coma:\n') unsorted = [int(item) for item in user_input.split(',')] - print heap_sort(unsorted) + print (heap_sort(unsorted))