From 74c652cc4f94597d084d1f11aa17a862288a7325 Mon Sep 17 00:00:00 2001 From: Pavel Date: Wed, 9 Oct 2019 17:26:19 +0300 Subject: [PATCH] [ADD] heap sort with pure function --- Python/heap_sort_pure.py | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/heap_sort_pure.py diff --git a/Python/heap_sort_pure.py b/Python/heap_sort_pure.py new file mode 100644 index 0000000..7d5f244 --- /dev/null +++ b/Python/heap_sort_pure.py @@ -0,0 +1,48 @@ +# Heap Sort + + +def heapify(arr, n, i): + largest = i + left = 2 * i + 1 # left = 2*i + 1 + right = 2 * i + 2 # right = 2*i + 2 + + # See if left child of root exists and is + # greater than root + if left < n and arr[i] < arr[left]: + largest = left + + # See if right child of root exists and is + # greater than root + if right < n and arr[largest] < arr[right]: + largest = right + + # Change root, if needed + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + heapify(arr, n, largest) + + +def heap_sort(input_list): + size = len(input_list) + result_array = input_list[:] + + # Build a max heap. + for i in range(size, -1, -1): + heapify(result_array, size, i) + + # One by one extract elements + for i in range(size-1, 0, -1): + result_array[i], result_array[0] = result_array[0], result_array[i] + heapify(result_array, i, 0) + + return result_array + + +if __name__ == '__main__': + sample = [12, 11, 13, 5, 6, 7] + + print("Sorted array:") + print(sample) + + print("Sorted array:") + print(heap_sort(sample))