From 2de8ac9ea3ef041a3f218c3faa875d1b09955d4c Mon Sep 17 00:00:00 2001 From: Satyam Singh <56315878+satcasm@users.noreply.github.com> Date: Sun, 31 Jan 2021 23:33:49 +0530 Subject: [PATCH] added heap sort in cpp (#54) * add binary search in js * added merge sort in c * added quick sort in cpp * modified quick sort * added heap sort * updated readme.md --- sorting/README.md | 1 + sorting/c-or-cpp/heap-sort.cpp | 66 ++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 sorting/c-or-cpp/heap-sort.cpp diff --git a/sorting/README.md b/sorting/README.md index b00bbae7..b7358847 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -7,6 +7,7 @@ 3. [Selection Sort](c-or-cpp/selection-sort.cpp) 4. [Merge Sort](c-or-cpp/merge-sort.c) 5. [Quick Sort](c-or-cpp/quick-sort.cpp) +6. [Heap Sort](c-or-cpp/heap-sort.cpp) ### C# diff --git a/sorting/c-or-cpp/heap-sort.cpp b/sorting/c-or-cpp/heap-sort.cpp new file mode 100644 index 00000000..26a7ff13 --- /dev/null +++ b/sorting/c-or-cpp/heap-sort.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +void heapify(int a[], int n, int i); +void heapSort(int a[], int n); + +// Driver code +int main() +{ + cout << "Enter the length of array" << endl; + int n; + cin >> n; + int *a = new int(n); + // Getting elements of array + cout << "Enter the elements of array" << endl; + for (int i = 0; i < n; i++) + cin >> a[i]; + cout << "Original array:\n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + heapSort(a, n); + cout << "\nSorted array:\n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + delete (a); + return 0; +} + +// To heapify a subtree rooted with node i which is an index in a[] +void heapify(int a[], int n, int i) +{ + int largest = i; // Initialize largest as root + int l = 2 * i + 1; + int r = 2 * i + 2; + + // If left child is larger than root + if (l < n && a[l] > a[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && a[r] > a[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + swap(a[i], a[largest]); + // Recursively heapify the affected sub-tree + heapify(a, n, largest); + } +} + + +void heapSort(int a[], int n) +{ + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(a, n, i); + // One by one extract an element from heap + for (int i = n - 1; i > 0; i--) + { + // Move current root to end + swap(a[0], a[i]); + // call max heapify on the reduced heap + heapify(a, i, 0); + } +}