Skip to content

Instantly share code, notes, and snippets.

@mmagm
Created May 14, 2012 11:22
Show Gist options
  • Save mmagm/2693436 to your computer and use it in GitHub Desktop.
Save mmagm/2693436 to your computer and use it in GitHub Desktop.
heap sort
class Array
def left(i)
2 * i + 1
end
def right(i)
2 * i + 2
end
def heapify(i, heapsize)
l = left(i)
r = right(i)
largest = i
largest = l if l < heapsize && self[l] > self[largest]
largest = r if r < heapsize && self[r] > self[largest]
if largest != i
self[i], self[largest] = self[largest], self[i]
heapify(largest, heapsize)
end
end
def build_max_heap
nodes = self.length / 2 - 1
nodes.downto(0) do |i|
heapify(i, self.length)
end
end
def heapsort
build_max_heap
start = self.length - 1
start.downto 1 do |i|
self[0], self[i] = self[i], self[0]
heapify(0, i)
end
return self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment