九章算法人工智能集訓營2022
Objective-C語言實現(xiàn):
- (NSArray *)mergeWithArray:(NSArray *)sourceArray
? ? ? ? ? ?startIndex:(NSInteger)startIndex
? ? ? ? ? ? ?midIndex:(NSInteger)midIndex
? ? ? ? ? ? ?endIndex:(NSInteger)endIndex{
? ?NSMutableArray *sourceMutableArray = [NSMutableArray arrayWithArray:sourceArray];
? ?NSMutableArray *tempMutableArray = [[NSMutableArray alloc] init];
? ?
? ?NSInteger i = startIndex;
? ?NSInteger j = midIndex + 1;
? ?NSInteger k = startIndex;
? ?while (i != midIndex && j != endIndex){
? ? ? ?if (sourceMutableArray[i] > sourceMutableArray[j]) {
? ? ? ? ? ?//tempMutableArray[k] = sourceMutableArray[j];
? ? ? ? ? ?[tempMutableArray replaceObjectAtIndex:k withObject:sourceMutableArray[j]];
? ? ? ? ? ?k ++;
? ? ? ? ? ?j ++;
? ? ? ?}else{
? ? ? ? ? ?//tempMutableArray[k] = sourceMutableArray[i];
? ? ? ? ? ?[tempMutableArray replaceObjectAtIndex:k withObject:sourceMutableArray[i]];
? ? ? ? ? ?k ++;
? ? ? ? ? ?i ++;
? ? ? ?}
? ?}
? ?while (i != midIndex + 1) {
? ? ? ?[tempMutableArray replaceObjectAtIndex:k withObject:sourceMutableArray[i]];
? ? ? ?k ++;
? ? ? ?i ++;
? ?}
? ?while (j != endIndex + 1) {
? ? ? ?[tempMutableArray replaceObjectAtIndex:k withObject:sourceMutableArray[j]];
? ? ? ?k ++;
? ? ? ?j ++;
? ?}
? ?for (i = startIndex; i < endIndex; i ++) {
? ? ? ?[sourceMutableArray replaceObjectAtIndex:i withObject:tempMutableArray[i]];
? ?}
? ?return sourceMutableArray;}- (NSArray *)mergeSortWithArray:(NSArray *)sourceArray
? ? ? ? ? ? ? ? ? ? startIndex:(NSInteger)startIndex
? ? ? ? ? ? ? ? ? ? ? endIndex:(NSInteger)endIndex{
? ?if (startIndex < endIndex) {
? ? ? ?NSInteger midIndex = (startIndex + endIndex)/2;
? ? ? ?NSArray *tempArray = ?[self mergeSortWithArray:sourceArray
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?startIndex:startIndex
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?endIndex:endIndex];
? ? ? ?NSArray *tempArray2 = [self mergeSortWithArray:tempArray
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?startIndex:midIndex + 1
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?endIndex:endIndex];
? ? ? ?return [self mergeWithArray:tempArray2
? ? ? ? ? ? ? ? ? ? ? ? startIndex:startIndex
? ? ? ? ? ? ? ? ? ? ? ? ? midIndex:midIndex
? ? ? ? ? ? ? ? ? ? ? ? ? endIndex:endIndex];
? ? ?
? ?}
? ?return nil;}