views:

628

answers:

2

I have an iPhone application that needs to sort a couple of NSMutableArrays, this arrays contain around 3000 elements.

The idea is to sort them once when the application starts, then every iteration I need to insert 9 elements to each of those arrays. Is there an efficient way with NSMutableArrays, to insert those 9 elements in a sorted way?

I don't know if sortUsingSelector: is "smart" enough to take advantage of the array being mostly sorted and only 9 elements being "unsorted".

Thanks!

+2  A: 

Best way to sort NSMutableArray? Use sortUsingSelector message. It should be smart enough.

To insert the elements in a sorted way you can previously do a binary search on the array, and then insert the element in the desired position.

Having answered your question, I would suggest you to consider using SQLite to store the elements you want for the array. That way, your problem will reduce to querying the table with the elements with an order by clause, and inserting the new 9 elements with insert sentence. If you have an index on the order you are looking for, it should be fast.

Pablo Santa Cruz
-1 It's not smart enough. The documentation alludes to this in the description of `sortedArrayUsingFunction:context:hint:`.
tc.
+1  A: 

I've have good success with just tossing elements into the array and then sorting it with the NSArray sorting methods.

It sounds inefficient but these Foundation classes aren't just lightweight wrappers around standard C arrays . Instead, they have a tremendous amount of code all built to make these standard task easy and quick.

A good rule of thumb is to use the quickest and easiest method provided by the built-in classes and then investigate a different methods only when you've proven the easy method isn't fast enough.

Premature optimization is the root of all evil.

TechZen