Created
March 29, 2011 13:54
-
-
Save Majkl578/892401 to your computer and use it in GitHub Desktop.
Heapsort on top of Ruby's array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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