快速排序

 

 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
)

 

posted @ 2017-02-04 10:48  Leo-Wmw  阅读(133)  评论(0编辑  收藏  举报