Created
August 20, 2013 15:21
-
-
Save lonelytango/6282881 to your computer and use it in GitHub Desktop.
Merge 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 *)mergeSort { | |
if ([self count] <= 1) { | |
return self; | |
} | |
NSArray *array1, *array2; | |
//If array count is odd | |
NSInteger arrayHalfSize = [self count] / 2; | |
if ([self count] % 2 == 1) { | |
array1 = [self subarrayWithRange:NSMakeRange(0, arrayHalfSize + 1)]; | |
array2 = [self subarrayWithRange:NSMakeRange(arrayHalfSize + 1, arrayHalfSize)]; | |
} else { | |
array1 = [self subarrayWithRange:NSMakeRange(0, arrayHalfSize)]; | |
array2 = [self subarrayWithRange:NSMakeRange(arrayHalfSize, arrayHalfSize)]; | |
} | |
return [self mergeArray1:[array1 mergeSort] withArray2:[array2 mergeSort]]; | |
} | |
- (NSArray *)mergeArray1:(NSArray *)array1 withArray2:(NSArray *)array2 { | |
NSMutableArray *mutableArray1 = [array1 mutableCopy]; | |
NSMutableArray *mutableArray2 = [array2 mutableCopy]; | |
NSMutableArray *mergedArray = [NSMutableArray new]; | |
while ([mutableArray1 count] > 0 && [mutableArray2 count] > 0) { | |
if ([mutableArray1[0] compare:mutableArray2[0]] == NSOrderedAscending) { | |
[mergedArray addObject:mutableArray1[0]]; | |
[mutableArray1 removeObjectAtIndex:0]; | |
} else { | |
[mergedArray addObject:mutableArray2[0]]; | |
[mutableArray2 removeObjectAtIndex:0]; | |
} | |
} | |
if ([mutableArray1 count] > 0) { | |
[mergedArray addObjectsFromArray:mutableArray1]; | |
} | |
if ([mutableArray2 count] > 0) { | |
[mergedArray addObjectsFromArray:mutableArray2]; | |
} | |
return [mergedArray copy]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment