How do I implement heap sort in Swift?

Heap sort is an efficient sorting algorithm that uses a binary heap data structure. It has a time complexity of O(n log n) and is an in-place sorting algorithm. Below, you'll find an example implementation of heap sort in Swift.

// Swift implementation of Heap Sort func heapify(_ array: inout [Int], _ n: Int, _ i: Int) { var largest = i let left = 2 * i + 1 let right = 2 * i + 2 if left < n && array[left] > array[largest] { largest = left } if right < n && array[right] > array[largest] { largest = right } if largest != i { array.swapAt(i, largest) heapify(&array, n, largest) } } func heapSort(_ array: inout [Int]) { let n = array.count for i in (n / 2 - 1).stride(through: 0, by: -1) { heapify(&array, n, i) } for i in (0..

heap sort sorting algorithm Swift binary heap time complexity