HeapSort is an efficient comparison-based sorting algorithm that utilizes a binary heap data structure. It has a time complexity of O(n log n) and does not require additional space, making it an in-place sorting algorithm.
HeapSort involves two main steps:
Here is the implementation of HeapSort in Go:
gopackage main
import (
"fmt"
)
// HeapSort function
func HeapSort(arr []int) {
n := len(arr)
// Build a max-heap
for i := n/2 - 1; i >= 0; i-- {
heapify(arr, n, i)
}
// One by one extract elements from the heap
for i := n - 1; i > 0; i-- {
// Move current root to end
arr[0], arr[i] = arr[i], arr[0]
// Call max heapify on the reduced heap
heapify(arr, i, 0)
}
}
// Heapify a subtree rooted at node i
func heapify(arr []int, n int, i int) {
largest := i // Initialize largest as root
left := 2*i + 1 // Left child
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 {
arr[i], arr[largest] = arr[largest], arr[i] // Swap
// Recursively heapify the affected sub-tree
heapify(arr, n, largest)
}
}
func main() {
arr := []int{12, 11, 13, 5, 6, 7}
fmt.Println("Unsorted array:", arr)
HeapSort(arr)
fmt.Println("Sorted array:", arr)
}
InsertionSort
BubbleSort
HeapSort is a robust, in-place sorting algorithm with a consistent O(n log n) time complexity. It is especially useful when space is a constraint. However, for practical purposes, QuickSort is often preferred due to its faster average-case performance, despite its potential O(n²) worst-case time complexity. MergeSort is another solid choice, particularly when stability is required, although it comes with higher space requirements. Understanding the strengths and weaknesses of each algorithm allows you to choose the right one for your specific needs.