Class: SISFC::SortedArray
- Inherits:
-
Array
- Object
- Array
- SISFC::SortedArray
- Defined in:
- lib/sisfc/sorted_array.rb
Overview
the SortedArray class was taken from the ruby cookbook
Instance Method Summary collapse
- #<<(el) ⇒ Object (also: #push, #unshift)
-
#initialize(*args, &sort_by) ⇒ SortedArray
constructor
A new instance of SortedArray.
- #insert(i, v) ⇒ Object
- #reverse! ⇒ Object
Constructor Details
#initialize(*args, &sort_by) ⇒ SortedArray
Returns a new instance of SortedArray.
6 7 8 9 10 |
# File 'lib/sisfc/sorted_array.rb', line 6 def initialize(*args, &sort_by) @sort_by = sort_by || Proc.new { |x,y| x <=> y } super(*args) sort! &sort_by end |
Instance Method Details
#<<(el) ⇒ Object Also known as: push, unshift
33 34 35 |
# File 'lib/sisfc/sorted_array.rb', line 33 def <<(el) insert(0, el) end |
#insert(i, v) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/sisfc/sorted_array.rb', line 12 def insert(i, v) if size == 0 or v < self[0] super(0, v) elsif v > self[-1] super(-1, v) else left = 0 right = size - 1 middle = (left + right)/2 while left < right if v >= self[middle] left = middle + 1 else right = middle end middle = (left + right)/2 end super(middle, v) end end |
#reverse! ⇒ Object
55 56 57 |
# File 'lib/sisfc/sorted_array.rb', line 55 def reverse! # do nothing: reversing the array would disorder it. end |