views:

155

answers:

1

Let's say I have a NSArray with 50-100 objects inside. How can I sort the array into a random order?

+4  A: 

There are a lot of ways to do it, but most will involve simply generating random numbers. Perhaps you could use this technique using an NSMutableArray:

  1. Generate a random number between 0 and 49 (assuming 50 elements)
  2. Swap elements 0 and whatever number you generate
  3. Generate a random number between 1 and 49
  4. Swap elements 1 and whatever number you generate
  5. Etc.

That would probably be the most efficient way.

Sample code (not tested):

srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++) {
    NSInteger randInt = (random() % ([array count] - x)) + x;
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}

Also, you could use two NSMutableArray objects, and simply loop through while the first has objects, choose one randomly, and add it to the end of the other one. The in place method is probably faster though.

jfm429
using arc4random() is much better!
nonamelive
This is a version of the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher–Yates_shuffle
JeremyP