C Online Compiler
Example: Heap Sort for 5 Numbers in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Heap Sort for 5 Numbers #include <stdio.h> // Function to heapify a subtree rooted with node i // n is size of heap void heapify(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) { // Swap int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Main function to do heap sort void heapSort(int arr[], int n) { // Step 1: Build a 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: One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // Function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) { printf("%d ", arr[i]); } printf("\n"); } int main() { // Step 1: Define the array of 5 numbers int arr[] = {4, 1, 3, 2, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Step 2: Apply Heap Sort heapSort(arr, n); printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS