快速排序
Posted 不忘初心,方得始终
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速排序相关的知识,希望对你有一定的参考价值。
1 #import "ViewController.h" 2 3 @interface ViewController () 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 // Do any additional setup after loading the view, typically from a nib. 12 NSMutableArray *arr = @[@"9", @"8", @"2", @"6", @"1"].mutableCopy; 13 [self QuickSort:arr StartIndex:0 EndIndex:4]; 14 NSLog(@"%@", arr); 15 } 16 17 -(void)QuickSort:(NSMutableArray *)list StartIndex:(NSInteger)startIndex EndIndex:(NSInteger)endIndex{ 18 19 if(startIndex >= endIndex)return; 20 21 NSNumber * temp = [list objectAtIndex:startIndex]; 22 NSInteger tempIndex = startIndex; //临时索引 处理交换位置(即下一个交换的对象的位置) 23 24 for(int i = (int)startIndex + 1 ; i <= endIndex ; i++){ 25 26 NSNumber *t = [list objectAtIndex:i]; 27 28 if([temp intValue] > [t intValue]){ 29 30 tempIndex = tempIndex + 1; 31 32 [list exchangeObjectAtIndex:tempIndex withObjectAtIndex:i]; 33 34 } 35 36 } 37 38 [list exchangeObjectAtIndex:tempIndex withObjectAtIndex:startIndex]; 39 [self QuickSort:list StartIndex:startIndex EndIndex:tempIndex-1]; 40 [self QuickSort:list StartIndex:tempIndex+1 EndIndex:endIndex]; 41 42 } 43 44 - (void)didReceiveMemoryWarning { 45 [super didReceiveMemoryWarning]; 46 // Dispose of any resources that can be recreated. 47 } 48 49 50 @end
打印结果
2016-12-22 17:56:14.546 text[31326:1735436] (
1,
2,
6,
8,
9
)
以上是关于快速排序的主要内容,如果未能解决你的问题,请参考以下文章