From bfe4e42e6777455c58e5241734da38a44d131d29 Mon Sep 17 00:00:00 2001 From: VIKING987 Date: Mon, 14 Oct 2019 19:31:50 +0530 Subject: [PATCH] added Heap Sort --- Sorting/HeapSort/HeapSort.cpp | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Sorting/HeapSort/HeapSort.cpp diff --git a/Sorting/HeapSort/HeapSort.cpp b/Sorting/HeapSort/HeapSort.cpp new file mode 100644 index 0000000..095823a --- /dev/null +++ b/Sorting/HeapSort/HeapSort.cpp @@ -0,0 +1,41 @@ +#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 (l < n && arr[l] > arr[largest]) + largest = l; + if (r < n && arr[r] > arr[largest]) + largest = r; + 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); + } +} +void printArray(int arr[], int n) +{ + for (int i=0; i