OC快速排序
好久没有回顾学过的东西了,今天要用到快排的时候居然忘记了,好记性不如烂笔头啊,回顾下快速排序
快速排序的思想简单明了,核心精髓在于分割
1:选基数,假设每次都取最左边的为基数,并假设该基数是最小的(最终结果也是升序,倒序也可以效仿)
2:划分,扫描所要排序的区间;小于基数的放到左侧,并且交换
3:分别对左侧和右侧重复第二部的操作
代码如下
//分割位置
-(NSInteger)partion:(NSMutableArray*)source lowPosition:(NSInteger)lowIndex HighPosition:(NSInteger)hightIndex
{
if (lowIndex==hightIndex) {
return lowIndex;
}
//假设取最左边为比较对象
NSNumber *base = source[lowIndex];
NSInteger i = lowIndex;//比较对象在数组中的索引位置
for (NSInteger j=lowIndex; j<=hightIndex; j++) {
if ([source[j]integerValue]<base.integerValue)//找到一个比比较对象小的位置就右移一位,同时交换改两个位置上的数
{
i++;
NSNumber *temp = source[i];
source[i] = source[j];
source[j] = temp;
}
}
//扫描完毕后把比较对象放在对应位置
NSNumber *temp2 = source[i];
source[i] = base;
source[lowIndex] = temp2;
return i;
}
-(void)quickSort:(NSMutableArray*)source startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
if (startIndex<endIndex) {
NSInteger partPosition = [selfpartion:sourcelowPosition:startIndexHighPosition:endIndex];
[selfquickSort:sourcestartIndex:startIndexendIndex:partPosition-1];
[selfquickSort:sourcestartIndex:partPosition+1endIndex:endIndex];
}
}
//检查验证
-(void)test{
NSMutableArray *arr = [[NSMutableArrayalloc]init];
for (int i=0; i<100; i++) {
int random = arc4random();
[arr addObject:@(random)];
}
[selfquickSort:arrstartIndex:0endIndex:arr.count-1];
for (NSNumber *itemin arr) {
NSLog(@"%@",item);
}
}
打印结果验证