Class: Wallace::Utility::SortedArray
- Inherits:
-
Array
- Object
- Array
- Wallace::Utility::SortedArray
- Defined in:
- lib/utility/sorted_array.rb
Instance Method Summary collapse
-
#<<(value) ⇒ Object
Inserts a value into the array at its correct sorted position.
-
#calculate_index(value) ⇒ Object
Calculates the correct index to insert the value into the array at.
-
#initialize(array = nil) ⇒ SortedArray
constructor
A new instance of SortedArray.
- #push(*values) ⇒ Object
- #set(values) ⇒ Object
Constructor Details
#initialize(array = nil) ⇒ SortedArray
Returns a new instance of SortedArray.
3 4 5 |
# File 'lib/utility/sorted_array.rb', line 3 def initialize(array = nil) super(array.sort) if array != nil end |
Instance Method Details
#<<(value) ⇒ Object
Inserts a value into the array at its correct sorted position.
12 13 14 |
# File 'lib/utility/sorted_array.rb', line 12 def <<(value) insert(calculate_index(value), value) end |
#calculate_index(value) ⇒ Object
Calculates the correct index to insert the value into the array at.
*TODO:*
-
This is a rubbish O(n) implementation.
| A RB-binary tree or a better insertion sort method should | be implemented.
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/utility/sorted_array.rb', line 28 def calculate_index(value) i = 0 self.each { |v| if v > value break end i += 1 } return i end |
#push(*values) ⇒ Object
16 17 18 19 |
# File 'lib/utility/sorted_array.rb', line 16 def push(*values) values.each{|v| self << v} return self end |
#set(values) ⇒ Object
7 8 9 |
# File 'lib/utility/sorted_array.rb', line 7 def set(values) end |