Created
July 31, 2015 08:47
-
-
Save 284km/2981de5921c1b25594d3 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
class Array | |
def quicksort | |
return self if size <= 1 | |
pivot = self[self.size / 2] | |
puts "# -------------------------------------------------------------------------" | |
puts "pivot: #{pivot}" | |
puts "self: #{self}" | |
i = 0 | |
j = self.size - 1 | |
loop do | |
i += 1 until self[i].to_i >= pivot && i < self.size | |
j -= 1 until self[j].to_i <= pivot && j >= 0 | |
puts "i: #{i} => #{self[i].to_i}, j: #{j} => #{self[j].to_i}" | |
break if i >= j | |
self[i], self[j] = self[j], self[i] | |
i += 1 | |
j -= 1 | |
puts "self: #{self}" | |
end | |
left = begin | |
self[0..self.index(pivot) - 1].quicksort if self.index(pivot) > 0 | |
end | |
right = self[self.index(pivot)..-1].quicksort | |
left.to_a.concat(right) | |
end | |
end | |
puts "# =========================================================================" | |
a = (1..10).to_a.shuffle | |
p a | |
p a.quicksort |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment