C++ Online Compiler
Example: Heap Sort for 5 Numbers in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Heap Sort for 5 Numbers #include <iostream> #include <vector> #include <algorithm> // For std::swap // Function to heapify a subtree rooted with node i // n is size of heap void heapify(std::vector<int>& arr, int n, int i) { int largest = i; // Initialize largest as root int left = 2 * i + 1; // Left child int right = 2 * i + 2; // Right child // If left child is larger than root if (left < n && arr[left] > arr[largest]) { largest = left; } // If right child is larger than largest so far if (right < n && arr[right] > arr[largest]) { largest = right; } // If largest is not root if (largest != i) { std::swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Main function to do heap sort void heapSort(std::vector<int>& arr, int n) { // Step 1: Build a max-heap (rearrange array) // Iterate from the last non-leaf node up to the root // (n/2 - 1) is the index of the last non-leaf node for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } // Step 2: One by one extract an element from heap // After building the max-heap, the largest element is at the root (index 0). // Swap it with the last element of the heap, then reduce the heap size // and heapify the new root. for (int i = n - 1; i > 0; i--) { // Move current root to end std::swap(arr[0], arr[i]); // Call max 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 the array of 5 numbers std::vector<int> numbers = {4, 1, 3, 2, 5}; int n = numbers.size(); std::cout << "Original array: "; printArray(numbers); // Step 2: Apply heap sort heapSort(numbers, n); std::cout << "Sorted array: "; printArray(numbers); return 0; }
Output
Clear
ADVERTISEMENTS