Skip to content

Instantly share code, notes, and snippets.

@bhelx
Last active October 10, 2016 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhelx/1149708 to your computer and use it in GitHub Desktop.
Save bhelx/1149708 to your computer and use it in GitHub Desktop.
BINARY SORT FOR EXERCISE.
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