Skip to content

Instantly share code, notes, and snippets.

@lonelytango
Last active December 21, 2015 08:18
Show Gist options
  • Save lonelytango/6276895 to your computer and use it in GitHub Desktop.
Save lonelytango/6276895 to your computer and use it in GitHub Desktop.
Insertion Sort (NSArray category)
- (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