4

I want to use a self balancing binary tree to play around with some algorithms, but I'm having difficulty finding the Ruby equivalent of Java's TreeSet (or C#'s SortedSet).

I have found web code like:

https://github.com/nahi/avl_tree#readme

https://github.com/MishaConway/binary_search_tree

http://blog.mikedll.com/2009/09/balanced-avl-binary-search-tree.html

I'd rather rely on something that is in Ruby's Standard Library. Isn't there some class in Ruby's Standard Library for this? I can't seem to find much besides RubyTree, which I don't believe is self-balancing.

(I'll keep Googling til I find it, or someone on this forum points me in the right direction :) )

Foolish Chap
  • 765
  • 1
  • 5
  • 19

1 Answers1

9

You can use SortedSet from set as shown below

require 'set'
 s = SortedSet.new([8,2,9,3])
 => #<SortedSet: {2, 3, 8, 9}>

pass argument array as paramter

Babasaheb Gosavi
  • 7,735
  • 1
  • 14
  • 14
  • So, if I wanted to determine the average amount of time it takes to look up a key in a randomly-generated balanced binary search tree, I could use SortedSet? I'm trying to see where it says SortedSet is implemented as a balanced binary search tree... hmmm – Foolish Chap Jan 17 '13 at 04:35
  • 2
    @FoolishChap It is a red-black tree. See https://github.com/ruby/ruby/blob/trunk/lib/set.rb#L540 – halfelf Jan 17 '13 at 05:28
  • In MRI, it is implemented using `Hash`, in all other Ruby implementations, it is implemented using some sort of self-balancing search tree. The Ruby Language Specification doesn't specify any particular data structure or algorithm; in fact, the Ruby Language Specification completely ignores the *entire* standard library. So, you cannot rely on that. – Jörg W Mittag Jan 17 '13 at 12:41