C Online Compiler
Example: Heap Sort in C in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Heap Sort in C #include <stdio.h> // Function to swap two integers void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // Function to heapify a subtree rooted with node i which is // an index in arr[]. 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(&arr[i], &arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Main function to sort an array of given size void heapSort(int arr[], int n) { // Step 1: Build a max-heap (rearrange array) // Start from the last non-leaf node and go up to the root 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 swap(&arr[0], &arr[i]); // Call 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: Initialize an array int arr[] = {12, 11, 13, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Step 2: Perform heap sort heapSort(arr, n); printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS