Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

If I am loading a whole load of items (un-ordered words from a file or something) would it be more efficient to load them all to a Ruby array, and then use the built in sort! method or to do a binary lookup for the place of each item in the list as I load it, and add it in that position.

Basic code:

array = []
lines.each do |line|
    array.push line
end
array.sort!

vs

array = []
lines.each do |line|
    array.insert(find_index(line), line)
end

find_index() would lookup the correct index for the item in the array using a binary search.

share|improve this question
1  
Have you profiled them for a small data set? –  MichaelT Sep 20 '13 at 4:34
add comment

1 Answer 1

up vote 3 down vote accepted

array.insert is O(n) for insertions in the middle (because it has to copy a part of the array), making the second variant O(n^2), while push is O(1), and sort! is O(n log n), so the first variant is only O(n log n). Also the first variant looks cleaner.

share|improve this answer
    
And there is no data structure that would minimise the insertions? –  JavaNut13 Sep 20 '13 at 5:05
    
You could use binary trees, but they, of course, have their own drawbacks (in terms of performance of certain operations, or memory footprint). And you do not need them for the particular task you have described here. –  Bogdan Sep 20 '13 at 5:12
    
I'm not 100% sure about this, but given its speed Ruby's sort is also probably written in C, not Ruby, so you'll get far better performance out of it than most anything you write by hand in Ruby to do a similar function. –  KChaloux Sep 20 '13 at 12:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.