快速排序

.h:

typedef enum {

QuickSortSequence_ascending = 99, //升序

QuickSortSequence_descending //降序

} QuickSortSequence;

@interface NSMutableArray (tool)

- (void)quickSortWithLeft:(int)leftNum andRight:(int)rightNum andSortSequence:(QuickSortSequence)quickSortSequence;

@end

.m

- (void)quickSortWithLeft:(int)leftNum andRight:(int)rightNum andSortSequence:(QuickSortSequence)quickSortSequence

{

if (leftNum > rightNum) {

return;

}

float poleNum = [[self objectAtIndex:leftNum] floatValue];

int i = leftNum, j = rightNum, t = 0;

while (i != j) {

//顺序很重要,要先从右往左找

while ((quickSortSequence == QuickSortSequence_descending ? [[self objectAtIndex:j] intValue] <= poleNum : [[self objectAtIndex:j] intValue] >= poleNum) && i < j) {

j--;

}

//再从左往右找

while ((quickSortSequence == QuickSortSequence_descending ? [[self objectAtIndex:i] intValue] >= poleNum : [[self objectAtIndex:i] intValue] <= poleNum) && i < j) {

i++;

}

//交换两个数组中的位置

if (i < j) //当哨兵i和哨兵j没有相遇的时候

{

t = [[self objectAtIndex:i] intValue];

[self replaceObjectAtIndex:i withObject:[self objectAtIndex:j]];

[self replaceObjectAtIndex:j withObject:@(t)];

}

}

//将基位数归位

[self replaceObjectAtIndex:leftNum withObject:[self objectAtIndex:i]];

[self replaceObjectAtIndex:i withObject:@(poleNum)];

[self quickSortWithLeft:leftNum andRight:(i - 1) andSortSequence:quickSortSequence];

[self quickSortWithLeft:(i + 1) andRight:rightNum andSortSequence:quickSortSequence];

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容