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

    NSArray *beforeSortArray = [[NSArray alloc] initWithObjects:
                                    @{@"id":@"1"},
                                    @{@"id":@"3"},
                                    @{@"id":@"4"},
                                    @{@"id":@"7"},
                                    @{@"id":@"8"},
                                    @{@"id":@"2"},
                                    @{@"id":@"6"},
                                    @{@"id":@"5"},
                                    @{@"id":@"13"},
                                    @{@"id":@"15"},
                                    @{@"id":@"12"},
                                    @{@"id":@"20"},
                                    @{@"id":@"28"},
                                    @{@"id":@""}
                                    ,nil];
        NSLog(@"排序前:%@",beforeSortArray);
    
        //方法一
        NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
        NSArray *sortArray = [NSArray arrayWithObject:sortDesc];
        [beforeSortArray sortedArrayUsingDescriptors:sortArray];
        
        NSLog(@"第一次排序前原来的数组:%@", beforeSortArray);
        NSArray *newArray = [beforeSortArray sortedArrayUsingDescriptors:sortArray];
        NSLog(@"第一次排序后原来的数组:%@", beforeSortArray);//看排序的时候,原数组元素顺序会不会改变
        NSLog(@"第一次排序后:%@",newArray);//验证排序结果
        
        
        //方法二
        NSComparator cmptr = ^(id obj1, id obj2){
            if ([[obj1 objectForKey:@"id"] integerValue] > [[obj2 objectForKey:@"id"] integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([[obj1 objectForKey:@"id"] integerValue] < [[obj2 objectForKey:@"id"] integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        };
        
        NSLog(@"第二次排序前原来的数组:%@", beforeSortArray);
        NSArray *afterSortArray = [beforeSortArray sortedArrayUsingComparator:cmptr];
        NSLog(@"第二次排序后原来的数组:%@", beforeSortArray);//看排序的时候,原数组元素顺序会不会改变
        NSLog(@"第二次排序后:%@",afterSortArray);//验证排序结果

    总结:排序的时候,原数组的顺序不会改变,第一次的排序结果其实并不理想,没有达到想要的效果;还是建议大家多用第二种方法吧,数组的排序还有其他的几种写法,我不太熟,所以就没有写了,希望大家能多交流

  • 相关阅读:
    HDOJ/HDU 2560 Buildings(嗯~水题)
    HDOJ/HDU 2555 人人都能参加第30届校田径运动会了(判断加排序~)
    POJ1703Find them, Catch them
    BZOJ2303: [Apio2011]方格染色
    BZOJ2809: [Apio2012]dispatching
    POJ1611The Suspects
    BZOJ2006: [NOI2010]超级钢琴
    BZOJ2288: 【POJ Challenge】生日礼物
    BZOJ1150: [CTSC2007]数据备份Backup
    洛谷P1316 P1824
  • 原文地址:https://www.cnblogs.com/shidaying/p/4689864.html
Copyright © 2011-2022 走看看