Skip to content

Instantly share code, notes, and snippets.

@bhelx

bhelx/binary_sort.rb

Last active Oct 10, 2016
Embed
What would you like to do?
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