Welcome to our comprehensive guide on C Heap Sort! In this lesson, we'll dive deep into the world of efficient sorting algorithms, specifically focusing on the Heap Sort method. Let's get started! 🎯
Heap Sort is a comparison-based sorting algorithm that uses the heap data structure to sort elements efficiently. It was introduced by J. W. J. Williams in 1964. Heap Sort is easy to understand and implement, making it a popular choice among beginners and intermediates alike. 💡
Before we dive into Heap Sort, let's understand how to create a Heap. A Max Heap is a complete binary tree where each parent node is greater than or equal to its child nodes. In a Min Heap, the opposite is true. Here's a simple example of building a Max Heap:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}
void build_heap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
}In the above code, we first define a swap function to swap two numbers. The heapify function is used to create a heap starting from the last non-leaf node and moving towards the root. The build_heap function constructs a heap from an array. 📝
Now that we have our heap, let's sort the array using the Heap Sort algorithm:
void heap_sort(int arr[], int n) {
build_heap(arr, n);
for (int i = n - 1; i > 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}In the above code, we first build a heap using the build_heap function. Then, we swap the first and last elements, and restore the heap property by calling heapify. We repeat this process until the array is sorted. ✅
Heap Sort is useful in scenarios where the input data is large, as it has a time complexity of O(n log n) in the average case. This makes it a valuable tool for real-world projects that require efficient sorting. 💡
What is the time complexity of Heap Sort in the worst case?
That's it for our C Heap Sort lesson! Practice the code examples, and don't hesitate to explore more on your own. Happy coding! 🎯💻🚀