Skip to content

Instantly share code, notes, and snippets.

@Majkl578
Created March 29, 2011 13:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Majkl578/892401 to your computer and use it in GitHub Desktop.
Save Majkl578/892401 to your computer and use it in GitHub Desktop.
Heapsort on top of Ruby's array
class Array
def heapsort!
#heapify
1.upto(self.length - 1) do |i|
#move up
child = i
while child > 0
parent = (child - 1) / 2
if self[parent] < self[child]
self[parent], self[child] = self[child], self[parent]
child = parent
else
break
end
end
end
#sort
i = self.length - 1
while i > 0
self[0], self[i] = self[i], self[0]
i -= 1
#move down
parent = 0
while parent * 2 + 1 <= i
child = parent * 2 + 1
if child < i && self[child] < self[child + 1]
child += 1
end
if self[parent] < self[child]
self[parent], self[child] = self[child], self[parent]
parent = child
else
break
end
end
end
end
end
foo = [5, 11, 7, 2, 19, 4, 8, 22, 1, 12]
foo.heapsort!
p foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment