Heap Sort Algorithm

Heap Sort Algorithm is a comparison-based sorting technique that utilizes the binary heap data structure to sort a sequence of elements in either ascending or descending order. The main idea behind the algorithm is to build a binary heap (either max-heap or min-heap) from the given input data, then repeatedly extract the root element and insert it into the sorted section of the array while maintaining the heap property. In the first step, the algorithm builds a max-heap for sorting in ascending order (or a min-heap for sorting in descending order) using the input data. This process involves iteratively comparing parent and child nodes and swapping them if they do not follow the heap property. Once the heap is constructed, the algorithm then repeatedly extracts the root element (the largest or smallest element in the heap) and swaps it with the last element of the unsorted part of the array until the entire array is sorted. After each extraction, the heap is restructured to maintain its properties. This process continues until the entire array is sorted, resulting in an efficient and in-place sorting algorithm with a time complexity of O(n log n) for both the best and worst cases.
package Sort

object HeapSort {

  /**
    * @param array - a sequence of unsorted integers
    * @return - sequence of sorted integers @array
    */

  def heapSort(arr: Array[Int]): Array[Int] = {
    val sortedArray = arr.clone

    def sift(start: Int, count: Int): Unit = {
      var root = start

      while (root * 2 + 1 < count) {
        var child = root * 2 + 1
        if (child < count - 1 && sortedArray(child) < sortedArray(child + 1)) {
          child += 1
        }
        if (sortedArray(root) < sortedArray(child)) {
          val t = sortedArray(root)
          sortedArray(root) = sortedArray(child)
          sortedArray(child) = t
          root = child
        }
        else return
      }
    }

    var count = sortedArray.length
    var start = count / 2 - 1
    var end = count - 1

    while (start >= 0) {
      sift(start, count)
      start -= 1
    }

    while (end > 0) {
      val t = sortedArray(end)
      sortedArray(end) = sortedArray(0)
      sortedArray(0) = t
      sift(0, end)
      end -= 1
    }
    sortedArray
  }

}

LANGUAGE:

DARK MODE: