Last active
December 21, 2015 08:18
-
-
Save lonelytango/6276895 to your computer and use it in GitHub Desktop.
Insertion Sort (NSArray category)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSArray *)insertionSort { | |
//Do nothing if the array has less than or only 1 object | |
if ([self count] <= 1) { | |
return self; | |
} | |
NSMutableArray *sortedArray = [self mutableCopy]; | |
for (int j = 1; j < [sortedArray count]; j++) { | |
NSNumber *key = sortedArray[j]; | |
int i = j - 1; | |
//A[i] > key | |
while (i >= 0 && [sortedArray[i] compare:key] == NSOrderedDescending) { | |
sortedArray[i+1] = sortedArray[i]; | |
i--; | |
} | |
sortedArray[i+1] = key; | |
} | |
return [sortedArray copy]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment