- (void)click{
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < 1000; i++) {
[array addObject:@(random()%10000)];
}
NSArray *sortArray = [self insertion_sortWithArray:array low:0 high:array.count -1];
NSLog(@"sortArray = %@",sortArray);
}
- (NSArray*)insertion_sortWithArray:(NSMutableArray*)array low:(NSInteger)low high:(NSInteger)high {
//判断递归结束
if(array == nil || array.count == 0){
return nil;
}
if (low >= high) {
return nil;
}
//取中值 low与middle比较时i++,high与middle比较时j--
NSInteger middle = low + (high - low)/2;
NSNumber *prmt = array[middle];
NSInteger i = low;
NSInteger j = high;
//开始排序,使得leftprmt
//low,hight两端同时遍历,提高效率
while (i <= j) {
// while ([array[i] compare:prmt] == NSOrderedAscending) { 该行与下一行作用相同
while ([array[i] intValue] < [prmt intValue]) {
i++;
}
// while ([array[j] compare:prmt] == NSOrderedDescending) { 该行与下一行作用相同
while ([array[j] intValue] > [prmt intValue]) {
j--;
}
//找到符合交换条件的i<=j,并进行交换
if(i <= j){
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
//完成交换之后i++,j--
i++;
j--;
}
}
//low是否符合快排条件
if (low < j) {
[self insertion_sortWithArray:array low:low high:j];
}
//high是否符合快排条件
if (high > i) {
[self insertion_sortWithArray:array low:i high:high];
}
//返回排序后的数组
return array;
}