Created
February 15, 2014 16:47
-
-
Save yoman07/9021835 to your computer and use it in GitHub Desktop.
Objective C Merge Sort
This file contains 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*) mergeSortArray:(NSArray*) arr { | |
if(arr.count <2) { | |
return arr; | |
} | |
NSUInteger middle = arr.count/2; | |
NSRange leftRange = {0,middle}; | |
NSArray *leftArray = [arr subarrayWithRange:leftRange]; | |
NSRange rightRange = {middle,arr.count-middle}; | |
NSArray *rightArray = [arr subarrayWithRange:rightRange]; | |
leftArray = [self mergeSortArray:leftArray]; | |
rightArray = [self mergeSortArray:rightArray]; | |
return [self mergeLeftArray:leftArray andRightArray:rightArray]; | |
} | |
- (NSArray*)mergeLeftArray:(NSArray*)leftArray andRightArray:(NSArray*)rightArray { | |
NSMutableArray *sortedArray = [[NSMutableArray alloc] init]; | |
NSMutableArray *mutableLeft = [leftArray mutableCopy]; | |
NSMutableArray *mutableRight = [rightArray mutableCopy]; | |
while (mutableLeft.count >0 || mutableRight.count >0) { | |
if(mutableLeft.count >0 && mutableRight.count >0) { | |
if([mutableLeft[0] floatValue] <= [mutableRight[0] floatValue]) { | |
[sortedArray addObject:mutableLeft[0] ]; | |
[mutableLeft removeObjectAtIndex:0]; | |
} else { | |
[sortedArray addObject:mutableRight[0]]; | |
[mutableRight removeObjectAtIndex:0]; | |
} | |
} else if(mutableLeft.count >0) { | |
[sortedArray addObject:mutableLeft[0]]; | |
[mutableLeft removeObjectAtIndex:0]; | |
} else { | |
[sortedArray addObject:mutableRight[0]]; | |
[mutableRight removeObjectAtIndex:0]; | |
} | |
} | |
return sortedArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment