归并排序Merge Sort

时间:2023-03-09 09:18:10
归并排序Merge Sort
 //C语言实现

 void mergeSort(int array[],int first, int last)
{
if (first < last)//拆分数列中元素只剩下两个的时候,不再拆分
{
int mid = (first + last) / ;
//递归拆分数组
mergeSort(array, first, mid);
mergeSort(array, mid + , last);
//归并两个数组
merge(array, first, mid, last);
}
} void merge(int array[], int first,int mid,int last)
{
int i = first, j = mid + , k = first;
int temp[last + ]; //从两个数列的第一个开始判断
while (i <= mid && j <= last)
if (array[i] <= array[j])
temp[k ++] = array[i ++];
else
temp[k ++] = array[j ++]; //如果有剩余,补充进入数组
while (i <= mid)
temp[k ++] = array[i ++];
while (j <= last)
temp[k ++] = array[j ++]; //复制数组
while (first <= last)
{
array[first] = temp[first];
first ++;
}
}
 //Objective-C实现
//通过NSMutableArray的Category实现 //.h文件
@interface NSMutableArray (ArraySort) - (void)mergeSort; @end //.m文件 #import "NSMutableArray+ArraySort.h" @implementation NSMutableArray (ArraySort) - (void)mergeSort
{
[self sortByStartIndex: endIndex:self.count - ];
} - (void)sortByStartIndex:(int)start endIndex:(int)end
{
if (start < end)
{
int mid = (start + end) / ;
[self sortByStartIndex:start endIndex:mid];
[self sortByStartIndex:mid + endIndex:end];
[self mergeByStartIndex:start midIndex:mid endIndex:end];
}
} - (void)mergeByStartIndex:(int)start midIndex:(int)mid endIndex:(int)end
{
int i = start,j = mid + ;
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:end + ]; while (i <= mid && j <= end)
if ([[self objectAtIndex:i] integerValue] <= [[self objectAtIndex:j] integerValue])
[tempArray addObject:[self objectAtIndex:i ++]];
else
[tempArray addObject:[self objectAtIndex:j ++]]; while (i <= mid)
[tempArray addObject:[self objectAtIndex:i ++]];
while (j <= end)
[tempArray addObject:[self objectAtIndex:j ++]]; for (id object in tempArray)
[self replaceObjectAtIndex:start++ withObject:object];
} @end