Heap Sort

Sort an array using the heap sort algorithm with O(n log n) time complexity.

Code

Algorithms
def heapify(a, n, i)
  largest, l, r = i, 2 * i + 1, 2 * i + 2
  largest = l if l < n && a[l] > a[largest]
  largest = r if r < n && a[r] > a[largest]
  if largest != i
    a[i], a[largest] = a[largest], a[i]
    heapify(a, n, largest)
  end
end

a = arr.dup
n = a.length
(n / 2 - 1).downto(0) { |i| heapify(a, n, i) }
(n - 1).downto(1) do |i|
  a[0], a[i] = a[i], a[0]
  heapify(a, i, 0)
end
a

Parameters

Array to sort

Server

More Ruby Snippets