Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ruby have a list type that keeps contents sorted as adds/deletes occur?

I need a datastructure in Ruby that keeps its elements sorted as elements are added or deleted and allows (at least) the ability to pop the first element off the list.

The closest thing I've found in the ruby docs is SortedSet. However, this doesn't seem to provide any way to access the elements by their index (or even pop the first element off)

These are the specific operations I need:

  • Add object to the list
  • Pop first object off of the list
  • Check if an object is in the list
  • Remove object from the list (by object, not by index)

Does ruby have anything built in for this, or are there any libraries I can grab that would give it to me? I could implement one without too much difficulty but I'd rather use a preexisting one if possible.

Currently I'm using Ruby 1.8, though switching to 1.9 would probably be ok.

EDIT:

Since there seems to be some confusion, the sorting I need isn't the order that the objects are inserted. I need the sorting to be based on the <=> operator. Generally I'll be popping the first element, processing that (which may generate new elements), adding new elements to the list, then repeating. The elements being added could end up anywhere in the sorting order, not just at the end.

like image 972
Herms Avatar asked Jan 23 '10 20:01

Herms


1 Answers

may want to condiser this 1.8-compatible gem for red black trees which does this (Ruby/RBTree):

http://www.geocities.co.jp/SiliconValley-PaloAlto/3388/rbtree/README.html

tree is always kept balanced, operations on the tree are O(log N)

there's also a red black tree implementation here:

http://github.com/kanwei/algorithms

Containers::RubyRBTreeMap

like image 52
jspcal Avatar answered Oct 06 '22 07:10

jspcal