C++ Online Compiler
Example: Heap Sort using Recursion in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Heap Sort using Recursion #include <iostream> #include <vector> // Using vector for dynamic array behavior, can also use raw arrays // Function to heapify a subtree rooted with node i // n is size of heap void heapify(std::vector<int>& arr, int n, int i) { // Step 1: Initialize largest as root int largest = i; int left = 2 * i + 1; // Left child int right = 2 * i + 2; // Right child // Step 2: If left child is larger than root if (left < n && arr[left] > arr[largest]) { largest = left; } // Step 3: If right child is larger than current largest if (right < n && arr[right] > arr[largest]) { largest = right; } // Step 4: If largest is not root if (largest != i) { std::swap(arr[i], arr[largest]); // Step 5: Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Main function to perform heap sort void heapSort(std::vector<int>& arr, int n) { // Step 1: Build max heap (rearrange array) // Start from the last non-leaf node and heapify downwards for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } // Step 2: Extract elements one by one from heap for (int i = n - 1; i > 0; i--) { // Move current root to end std::swap(arr[0], arr[i]); // Call heapify on the reduced heap heapify(arr, i, 0); } } // Function to print an array void printArray(const std::vector<int>& arr) { for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; } int main() { // Step 1: Define an array to be sorted std::vector<int> arr = {12, 11, 13, 5, 6, 7}; int n = arr.size(); std::cout << "Original array: "; printArray(arr); // Step 2: Perform heap sort heapSort(arr, n); std::cout << "Sorted array: "; printArray(arr); // Step 3: Test with another array std::vector<int> arr2 = {4, 10, 3, 5, 1}; n = arr2.size(); std::cout << "Original array 2: "; printArray(arr2); heapSort(arr2, n); std::cout << "Sorted array 2: "; printArray(arr2); return 0; }
Output
Clear
ADVERTISEMENTS