Last active
October 10, 2016 20:10
-
-
Save bhelx/1149708 to your computer and use it in GitHub Desktop.
BINARY SORT FOR EXERCISE.
This file contains 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 BinaryTree | |
attr_accessor :value, :left, :right | |
def insert(value) | |
if @value | |
if value < @value | |
@left ||= BinaryTree.new | |
@left.insert(value) | |
else | |
@right ||= BinaryTree.new | |
@right.insert(value) | |
end | |
else | |
@value = value | |
end | |
end | |
def traverse_sort(s_array) | |
@left.traverse_sort(s_array) if @left | |
s_array.push @value | |
@right.traverse_sort(s_array) if @right | |
s_array | |
end | |
def self.bin_sort(array) | |
root = BinaryTree.new | |
array.each do |item| | |
root.insert(item) | |
end | |
root.traverse_sort([]) | |
end | |
end | |
shuffled = [*1..10].shuffle | |
puts "Shuffled: #{shuffled.join(' ')}" | |
puts "Sorted: #{BinaryTree.bin_sort(shuffled).join(' ')}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment