我试图弄清楚这个合并排序实现有什么问题。我已经把它缩小到当我连接左右数组的剩余部分时。在递归的第三个循环中,出现了问题。
-(NSArray *)mergeSort:(NSArray *)unsortedArray
{
//unsortedArray is 4,2,6,5,3,9
if ([unsortedArray count] < 2)
{
return unsortedArray;
}
int middle = ([unsortedArray count]/2);
NSRange left = NSMakeRange(0, middle);
NSRange right = NSMakeRange(middle, ([unsortedArray count] - middle));
NSArray *rightArr = [unsortedArray subarrayWithRange:right];
NSArray *leftArr = [unsortedArray subarrayWithRange:left];
return [self merge:[self mergeSort:leftArr] andRight:[self mergeSort:rightArr]];
}
-(NSArray *)merge:(NSArray *)leftArr andRight:(NSArray *)rightArr
{
NSMutableArray *result = [[NSMutableArray alloc]init];
int right = 0;
int left = 0;
while (left < [leftArr count] && right < [rightArr count])
{
if ([leftArr objectAtIndex:left] < [rightArr objectAtIndex:right])
{
[result addObject:[leftArr objectAtIndex:left++]];
}
else
{
[result addObject:[rightArr objectAtIndex:right++]];
}
}
NSRange leftRange = NSMakeRange(left, ([leftArr count] - left));
NSRange rightRange = NSMakeRange(right, ([rightArr count] - right));
NSArray *newRight = [rightArr subarrayWithRange:rightRange];
NSArray *newLeft = [leftArr subarrayWithRange:leftRange];
newLeft = [result arrayByAddingObjectsFromArray:newLeft];
return [newLeft arrayByAddingObjectsFromArray:newRight];
}
顺便说一句,这不是家庭作业。我是一名自学成才的程序员,试图学习一点 CS。感谢大家。