思路:
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
解答:
#import <Foundation/Foundation.h>
// 快速 排序 (从小到大)
void quickSort(NSMutableArray <NSNumber *> *numberArray, NSInteger startIndex, NSInteger endIndex) {
if (startIndex >= endIndex) {
return;
}
if(numberArray.count == 0) {
return;
}
if (numberArray.count == 1) {
return;
}
NSInteger leftIndex = startIndex;
NSInteger rightIndex = endIndex;
NSNumber *compareNumberValue = numberArray[startIndex];
while (leftIndex < rightIndex) {
while (leftIndex < rightIndex && compareNumberValue.integerValue <= numberArray[rightIndex].integerValue) {
rightIndex--;
}
numberArray[leftIndex] = numberArray[rightIndex];
while (leftIndex < rightIndex && compareNumberValue.integerValue >= numberArray[leftIndex].integerValue) {
leftIndex++;
}
numberArray[rightIndex] = numberArray[leftIndex];
}
numberArray[leftIndex] = compareNumberValue;
quickSort(numberArray, startIndex, leftIndex - 1);
quickSort(numberArray, leftIndex + 1, endIndex);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray <NSNumber *> *tmpArray = @[@1, @5, @10, @2, @8, @3, @4, @6, @7, @9];
NSMutableArray <NSNumber *>*tmpMutableArray = [NSMutableArray arrayWithArray:tmpArray];
quickSort(tmpMutableArray, 0, tmpArray.count - 1);
[tmpMutableArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%ld ", obj.integerValue);
}];
}
return 0;
}
网友评论