cocoa touch - Is there any built in method for sorting in Objective-c? -
i have 2 sorted nsmutablearrays
(or can use other collection, not critical), need insert objects first array second , preserve sort order in second array. optimal (fastest) method that? can implement known algorithms, question is, if there built-in method? if not, best algorithm in case?
the real answer be: it depends, since asking: fastest way of inserting objects 1 array while preserving sort order.
there no built in way of inserting in right place of sorted array. can achieve same effect adding 2 arrays won't "the fastest way".
what faster depends on many things like: how data arrays contain, ratio of data in array1 vs array2 (does 1 array contain more data other)?, etc.
note: should begin simple solution , optimize once experience performance problems. measurements large data set though, see solution works whatever data users may have.
inserting items 1 sorted array sorted array
if want merge 2 arrays inserting objects in right place normal algorithms apply. should insert smaller array bigger array , try insert entire sorted sequences possible instead of every item 1 one.
for best performance should try make batch insert using insertobjects:atindexes:
instead of inserting object 1 one.
you can use indexofobject:insortedrange:options:usingcomparator:
find index each item should inserted in other array if specify nsbinarysearchinginsertionindex
options. also, comparator using must same comparator sorted array, otherwise result "undefined".
with in mind this
create mutable index every item in smaller array find index insert item in longer array add (the insertion location + location in short array) index in mutable set. next item. batch insert items.
the documentation insertobjects:atindexes:
tells "the corresponding location specified in indexes after earlier insertions have been made." in case 2 sorted array mean items lower index have been added , should add index of object in short array value returned indexofobject:insortedrange:options:usingcomparator:
.
another (probably premature optimization) can decrease sortedrange every item in loop don't have search through parts of array know item inserted bigger than.
there many other optimizations can made. should still measure first! started.
Comments
Post a Comment