From ebf970302564e69710e135a174f56b0ccc350ddd Mon Sep 17 00:00:00 2001 From: Aviral Srivastava <63746541+Aviral-3@users.noreply.github.com> Date: Sun, 24 Oct 2021 21:25:58 +0530 Subject: [PATCH] Created Heap Sort Heap sort is a comparison-based sorting technique based on Binary Heap data structure. --- Heap Sort.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Heap Sort.cpp diff --git a/Heap Sort.cpp b/Heap Sort.cpp new file mode 100644 index 0000000..aab3ba9 --- /dev/null +++ b/Heap Sort.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; +void heapify(int arr[], int n, int i) { + int temp; + int largest = i; + int l = 2 * i + 1; + int r = 2 * i + 2; + if (l < n && arr[l] > arr[largest]) + largest = l; + if (r < n && arr[r] > arr[largest]) + largest = r; + if (largest != i) { + temp = arr[i]; + arr[i] = arr[largest]; + arr[largest] = temp; + heapify(arr, n, largest); + } +} +void heapSort(int arr[], int n) { + int temp; + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + for (int i = n - 1; i >= 0; i--) { + temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + heapify(arr, i, 0); + } +} +int main() { + int arr[] = { 20, 7, 1, 54, 10, 15, 90, 23, 77, 25}; + int n = 10; +i nt i; + cout<<"Given array is: "<