Overview
Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure. It divides the input into a sorted and an unsorted region and iteratively shrinks the unsorted region by extracting the largest element from the heap and moving it to the sorted region.
Program Structure
The following C program implements the heap sort algorithm. It consists of the following main parts:
- Heapify Function: This function maintains the heap property. It assumes the binary tree rooted at index i is a heap, but the subtree rooted at index i might not be.
- Heap Sort Function: This function builds a heap from the input data and then repeatedly extracts the maximum element to produce a sorted array.
- Main Function: This function handles input and output, calling the heap sort function and displaying the sorted array.
Heap Sort Program
#include
// Function to heapify a subtree rooted with node i which is
// an index in arr[]. n is the size of the heap
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2
// 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) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}
// Main function to do heap sort
void heapSort(int arr[], int n) {
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// 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 heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\\n");
}
// Driver program
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
printf("Sorted array is: \\n");
printArray(arr, n);
return 0;
}
How to Compile and Run
To compile and run the program, follow these steps:
- Save the code in a file named
heapsort.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using the command:
gcc heapsort.c -o heapsort
- Run the program with the command:
./heapsort
Output
Upon running the program, you should see the following output:
Sorted array is:
5 6 7 11 12 13
Conclusion
The heap sort algorithm is efficient with a time complexity of O(n log n) and can be implemented in-place. This makes it a useful sorting technique in scenarios where memory usage is a concern.