From 358fa077350bc1bd9a0dfad11748c2b1fe6eeb2c Mon Sep 17 00:00:00 2001 From: thebrahminator Date: Tue, 2 Oct 2018 21:41:04 +0530 Subject: [PATCH] This add Heap Sort This adds Heap Sort to the repository. Closes https://github.com/AllAlgorithms/cpp/issues/6 --- README.md | 2 +- sorting/heap_sort.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 sorting/heap_sort.cpp diff --git a/README.md b/README.md index 6886d0f2..13a9454d 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ - [Sorting](sorting) - [Strings](strings) - [Traversals](traversals) - +- [Heap Sort](sorting/heap_sort.cpp) ## License This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp new file mode 100644 index 00000000..4862b94f --- /dev/null +++ b/sorting/heap_sort.cpp @@ -0,0 +1,60 @@ +#include + +using namespace std; + +void heapify(int input[], int n, int i) +{ + + int largest = i; // Assign the largest as root + int left = 2*i + 1; // Calculate the index of left element + int right = 2*i + 2; // Calculate the index of right element + + //Checking if the left is larger than current large value + if (left < n && input[left] > input[largest]) + largest = left; + + //Checking if the right is larger than current large value + if (right < n && input[right] > input[largest]) + largest = right; + + if (largest != i) + { + swap(input[i], input[largest]); + + heapify(input, n, largest); + } +} + +void heapSort(int input[], int n) +{ // Function to perform heap sort. + + // Building the heap, effectively rearranging the array. + for (int i = n / 2 - 1; i >= 0; i--) + heapify(input, n, i); + + for (int i=n-1; i>=0; i--) + { + swap(input[0], input[i]); + heapify(input, i, 0); + } +} + +int main() +{ + int n; + cout<<"Enter the number of elements"<>n; + int array[n]; + cout<<"Enter the elements of array"<>array[i]; + } + heapSort(array, n); + cout << "Sorted array is \n"; + for(int i=0; i