Use insertion sort, find the location to insert using a binary search,
insertion loop would look like this:
start = 0
end = array count
if array empty
add item, go to next item.
1. search position = start + ((end - start) / 2), round down
2. if insert item equals item at search position, exit search and go to next item to insert
3. else if insert item is greater than the item at search position,
if search position equals end
insert at end
else
start = search position + 1
4. else
if search position equals start
insert before start
else
end = search position
5. if start equals end
insert item after start.
6. else
go to 1
so you get the insertion of a NSMutableSet, unique values and sorted, and save the need to copy.
Main Topics
Browse All Topics





by: AJViennaPosted on 2008-11-05 at 11:59:25ID: 22889127
You could use a NSMutableSet. A set can contain each value only once. Add random numbers until the set has the required size. And then copy it to an NSMutableArray (using NSEnumerator).
However, this is only a useful approach if the number of random numbers is quite large. In your case the number of generated random numbers is very small. It is probably much easier and faster to iterate for each random number over the NSMutableArray to find the right position and to insert the new random number at the right position (using insertObject:atIndex:). This way it is also sorted (insert-sort) during creating.