Random sort NSArray

This tutorial gives you information on how to sort an array randomly.

First you need to have a function that handles the randomization.

int randomSort(id obj1, id obj2, void *context ) {
 // returns random number -1 0 1
 return (arc4random()%2);    
}

Then you could call this function to any array you wanted to sort randomly.

[arrayObject sortUsingFunction:randomSort context:nil];

Or you can use this one as much properly implemented random sorting of array.

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

 

Happy Coding :)

Advertisement
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.