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
No trackbacks yet.