码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2016-12-22 20:29:29      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:sources   isp   nal   view   void   import   geo   pos   hang   

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSMutableArray *arr = @[@"9", @"8", @"2", @"6", @"1"].mutableCopy;
 [self QuickSort:arr StartIndex:0 EndIndex:4];
    NSLog(@"%@", arr);
}

-(void)QuickSort:(NSMutableArray *)list StartIndex:(NSInteger)startIndex EndIndex:(NSInteger)endIndex{
    
    if(startIndex >= endIndex)return;
    
    NSNumber * temp = [list objectAtIndex:startIndex];
    NSInteger tempIndex = startIndex; //临时索引 处理交换位置(即下一个交换的对象的位置)
    
    for(int i = (int)startIndex + 1 ; i <= endIndex ; i++){
        
        NSNumber *t = [list objectAtIndex:i];
        
        if([temp intValue] > [t intValue]){
            
            tempIndex = tempIndex + 1;
            
            [list exchangeObjectAtIndex:tempIndex withObjectAtIndex:i];
            
        }
        
    }
    
    [list exchangeObjectAtIndex:tempIndex withObjectAtIndex:startIndex];
    [self QuickSort:list StartIndex:startIndex EndIndex:tempIndex-1];
    [self QuickSort:list StartIndex:tempIndex+1 EndIndex:endIndex];
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

 

打印结果

2016-12-22 17:56:14.546 text[31326:1735436] (
    1,
    2,
    6,
    8,
    9
)

快速排序

标签:sources   isp   nal   view   void   import   geo   pos   hang   

原文地址:http://www.cnblogs.com/menglingxu/p/6212353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!