Posted By

jatkins on 06/30/10


Tagged

sort array arrays sorting order


Versions (?)

Insert a value into a numerically-ordered array in the correct order


 / Published in: Ruby
 

Public domain. Only works for integers. Passing update_array as "true" will return the original array with the new value inserted in the appropriate position; ignoring update_array will return the index at which the new value should be inserted.

  1. def insert_value_in_order(array_of_values, new_value, update_array = nil)
  2. value_index = array_of_values.index(new_value)
  3. index = 0
  4. if !value_index && array_of_values.last.to_i > new_value
  5. i = 0
  6. while array_of_values[i].to_i < new_value do
  7. i += 1
  8. end
  9. index = i
  10. else
  11. index = value_index ? value_index : -1
  12. end
  13. return update_array == true || update_array == 1 ? array_of_values.insert(index, new_value) : index
  14. end

Report this snippet  

You need to login to post a comment.