归并排序

/**

O(n log n）的时间复杂度。代价是需要额外的内存空间。
*/

/**

@param leftArray leftArray
@param rightArray rightArray
@return NSArray
*/

``````NSArray *merger(NSArray *leftArray, NSArray *rightArray) {
NSUInteger capacity = leftArray.count+rightArray.count;
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:capacity];
for (NSInteger index=0, i = 0, j=0; index < capacity; index++) {
if (i>=leftArray.count) {
arrayM[index] = rightArray[j++];
} else if (j >= rightArray.count) {
arrayM[index] = leftArray[i++];
} else if (leftArray[i] > rightArray[j]) {
arrayM[index] = rightArray[j++];
} else {
arrayM[index] = leftArray[i++];
}
}
return arrayM.copy;
}
``````

/**

@param array array
@return 返回排序好的数组
*/

``````NSArray *mergerSort(NSArray *array){
if (array.count<2) {
return array;
}
NSUInteger count = array.count;
NSUInteger mid =array.count/2;
NSArray *leftArray = [array subarrayWithRange:NSMakeRange(0, mid)];
NSArray *rightArray = [array subarrayWithRange:NSMakeRange(mid, count-mid)];
return merger(mergerSort(leftArray), mergerSort(rightArray));
}

``````