-(NSMutableArray*)bubbleSortDictionaryByKeys:(NSDictionary*)dict
{
//this method takes an NSDictionary and performs a basic bubblesort
//on its keys. It then returns those ordered keys as an NSMutableArray.
//You can then traverse the original NSDictionary and retrive its
//ordered objects by simply stepping through each key in the NSMutableArray.
if(!dict)
return nil;
NSMutableArray *sortedKeys = [NSMutableArray arrayWithArray: [dict allKeys]];
if([sortedKeys count] <= 0)
return nil;
else if([sortedKeys count] == 1)
return sortedKeys; //no sort needed
//perform bubble sort on keys:
int n = [sortedKeys count] -1;
int i;
BOOL swapped = YES;
NSString *key1,*key2;
NSComparisonResult result;
while(swapped)
{
swapped = NO;
for(i=0;i<n;i++)
{
key1 = [sortedKeys objectAtIndex: i];
key2 = [sortedKeys objectAtIndex: i+1];
//here is where we do our basic NSString comparison
//This can be easily customized.
//See the options for -compare: in NSString docs
result = [key1 compare: key2 options: NSCaseInsensitiveSearch];
if(result == NSOrderedDescending)
{
//we retain for good form, but these
//objects should still be safely
//retained by the dictionary:
[key1 retain];
[key2 retain];
//pop the two keys out of the array
[sortedKeys removeObjectAtIndex: i]; // key1
[sortedKeys removeObjectAtIndex: i]; // key2
//replace them
[sortedKeys insertObject: key1 atIndex: i];
[sortedKeys insertObject: key2 atIndex: i];
[key1 release];
[key2 release];
swapped = YES;
}
}
}
return sortedKeys;
}
leothenerd 11:04 pm on December 19, 2009