我想弄清楚這個合併排序實現有什麼問題。當我將左右數組的剩餘部分連接在一起時,我縮小了範圍。在遞歸的第三個循環中,出現了一些錯誤。合併排序Objective-C
-(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。感謝大家。
你是什麼意思「出現問題」?什麼是錯誤的行爲? – Fred
對於給定數組,輸出不是升序。 –