.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];
}