zoukankan      html  css  js  c++  java
  • ios数组排序

    - (void) sortMethod {
        NSComparator cmptr = ^(id obj1, id obj2) {
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1 integerValue] < [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            
            return (NSComparisonResult) NSOrderedSame;
        };
        
        NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
    
        //排序前
        NSLog(@"排序前:%@",[self formatOutPut:sortArray]);
        
        //第一种排序
        NSArray * array = [sortArray sortedArrayUsingComparator:cmptr];
        
        NSLog(@"排序后:%@",[self formatOutPut:array]);
        
        //第二种排序:利用sortedArrayUsingFunction 调用 对应方法customSort,这个方法中的obj1和obj2分别是指数组中的对象。
    
        array = [sortArray sortedArrayUsingFunction:customSort context:nil];
        NSLog(@"排序后:%@",[self formatOutPut:array]);
    
        
    }
    
    - (NSString *) formatOutPut:(NSArray *) array {
        NSMutableString * output = [[NSMutableString alloc] init];
        for (NSString * str in array) {
            [output appendFormat:@"%@ ",str];
        }
    
        return [output autorelease];
    }
                  
    
    NSInteger customSort(id obj1, id obj2,void* context){
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    };
  • 相关阅读:
    tomcat修改端口
    JSP_大并发_秒杀
    Nexus刷官方下载的映像_occam
    Nexus杂
    多项式ADT加法乘法——数组实现
    单链表——游标实现
    链表基本操作实现
    二叉查找树
    AVL树
    ORM框架疏理——廖雪峰实战系列(一)
  • 原文地址:https://www.cnblogs.com/benbenzhu/p/3431857.html
Copyright © 2011-2022 走看看