From ef619bdde5a9a6528e6308eef5c991fccd2ac63f Mon Sep 17 00:00:00 2001 From: Vaibhav Varshney Date: Wed, 5 Oct 2022 22:08:50 +0530 Subject: [PATCH] added heap sort algo An algo for heap sort --- Python/Sorting-Techniques/heapSort.py | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/Sorting-Techniques/heapSort.py diff --git a/Python/Sorting-Techniques/heapSort.py b/Python/Sorting-Techniques/heapSort.py new file mode 100644 index 00000000..f934d145 --- /dev/null +++ b/Python/Sorting-Techniques/heapSort.py @@ -0,0 +1,36 @@ +def heapify(arr, N, i): + largest = i + l = 2 * i + 1 + r = 2 * i + 2 + + if l < N and arr[largest] < arr[l]: + largest = l + + if r < N and arr[largest] < arr[r]: + largest = r + + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + + heapify(arr, N, largest) + +def heapSort(arr): + N = len(arr) + + for i in range(N//2 - 1, -1, -1): + heapify(arr, N, i) + + for i in range(N-1, 0, -1): + arr[i], arr[0] = arr[0], arr[i] + heapify(arr, i, 0) + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + + heapSort(arr) + N = len(arr) + + print("Sorted array is") + for i in range(N): + print("%d" % arr[i], end=" ") +