排序-系统compare排序

懒-直接贴出来代码了

//
//  ViewController.m
//  DDD
//
//  Created by luckyCoderCai on 16/8/11.
//  Copyright © 2016年 luckyCoderCai. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

/**
 *  需求描述:
    对多个账单按照时间排序
    逾期越久的放列表上面,未逾期的距离越近的优先列表上面
    可能嘴笨:举个例子
    四个账单,应还时间分别是 2016/06/06  2016/07/07 2016/09/09 2016/10/10
    注:当前时间是2016年08月13日15:01:21
    上面四个账单在列表中排序就是:
    
    2016/06/06
    2016/07/07
    -----以上为逾期的 以下为待还的-----
    2016/09/09
    2016/10/10
 */

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    /**
     *  我将系统当前时间 账单应还时间 都转成时间戳,拿当前时间的时间戳减去应还时间的时间戳
        这样:如果大于0 则逾期;小于等于0 则未逾期
     */
    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"-26", @"15", @"-8", @"67", @"1", @"-9", @"30", nil];
    for (int i = 0; i < arr.count; i ++) {
        for (int j = 0; j < arr.count - i - 1; j ++) {
            
            NSString *mm = [arr objectAtIndex:j];
            NSString *dd = [arr objectAtIndex:(j + 1)];
            
            if([mm compare:dd options:NSNumericSearch] == -1){//升序
            [arr exchangeObjectAtIndex:j withObjectAtIndex:(j + 1)];
                
            }
        }
    }
    
    /**
     *  排完序 结果为:
     (
     67,
     30,
     15,
     1,
     "-26",
     "-9",
     "-8"
     )
    逾期的达到想要的效果了
     未逾期的没有
     */
    NSLog(@"---%@", arr);
    
    /**
     *  这里将逾期的 和 未逾期的分离开
     */
    NSMutableArray *yuqi = [NSMutableArray array];
    NSMutableArray *notyuqi = [NSMutableArray array];
    
    for ( int i = 0; i < arr.count; i ++) {
        if ([arr[i] integerValue]<= 0) {//未逾期
            [notyuqi addObject:arr[i]];
        }else {
            [yuqi addObject:arr[i]];
        }
    }
    
    /**
     *  单独排序 未逾期的
     */
    for (int i = 0; i < notyuqi.count; i ++) {
        for (int j = 0; j < notyuqi.count - i - 1; j ++) {
            
            NSString *mm = [notyuqi objectAtIndex:j];
            NSString *dd = [notyuqi objectAtIndex:(j + 1)];
            
            if([mm compare:dd options:NSNumericSearch] == 1){//降序
                
                [notyuqi exchangeObjectAtIndex:j withObjectAtIndex:(j + 1)];
                
            }
            
        }
    }
    
    /**
     *  这里先把之前分离出的逾期的添加进数组  再把刚排序好的未逾期的数据添加进数组
        OK
     */
    NSMutableArray *cai = [NSMutableArray array];
    [cai addObjectsFromArray:yuqi];
    [cai addObjectsFromArray:notyuqi];
    
    /**
     *  结果:
     (
     67,
     30,
     15,
     1,
     "-8",
     "-9",
     "-26"
     )
     */
    NSLog(@"-cai --%@", cai);
    
}

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

@end

你可能感兴趣的:(排序-系统compare排序)