From 9b45ee23d3b8f6396401b52c2af6b8ccbf8981ea Mon Sep 17 00:00:00 2001 From: Jayshah-JS1312 <55508873+Jayshah-JS1312@users.noreply.github.com> Date: Sat, 12 Oct 2019 16:59:19 +0530 Subject: [PATCH] HeapSort program in c++ --- data_structures/sortings/HeapSort.cpp | 42 +++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 data_structures/sortings/HeapSort.cpp diff --git a/data_structures/sortings/HeapSort.cpp b/data_structures/sortings/HeapSort.cpp new file mode 100644 index 0000000..5517363 --- /dev/null +++ b/data_structures/sortings/HeapSort.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +using namespace std; +void heapify(int arr[], int n, int i) +{ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + if (r < n && arr[r] > arr[largest]) + largest = r; + if (l < n && arr[l] > arr[largest]) + largest = l; + if (largest != i) + { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } +} +void heapSort(int arr[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + for (int i=n-1; i>=0; i--) + { + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} +int main() +{ + int arr[] = {12, 14, 2, 3, 9, 8}; + int n = sizeof(arr)/sizeof(arr[0]); + + heapSort(arr, n); + + cout << "Array after sorting is: \n"; + for (int i=0; i