iOS之数组的排序(升序、降序及乱序)

 1 #pragma mark -- 数组排序方法(升序)
 2 
 3 - (void)arraySortASC{
 4 
 5     //数组排序
 6 
 7     //定义一个数字数组
 8 
 9     NSArray *array = @[@(3),@(4),@(2),@(1)];
10 
11     //对数组进行排序
12 
13     NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
14 
15         NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
16 
17         return [obj1 compare:obj2]; //升序
18 
19     }];
20 
21     NSLog(@"result=%@",result);
22 
23 }
24 
25  
26 
27 #pragma mark -- 数组排序方法(降序)
28 
29 - (void)arraySortDESC{
30 
31     //数组排序
32 
33     //定义一个数字数组
34 
35     NSArray *array = @[@(3),@(4),@(2),@(1)];
36 
37     //对数组进行排序
38 
39     NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
40 
41         NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
42 
43         return [obj2 compare:obj1]; //降序
44 
45     }];
46 
47     NSLog(@"result=%@",result);
48 
49 }
50 
51  
52 
53 #pragma mark -- 数组排序方法(乱序)
54 
55 - (void)arraySortBreak{
56 
57     //数组排序
58 
59     //定义一个数字数组
60 
61     NSArray *array = @[@(3),@(4),@(2),@(1),@(5),@(6),@(0)];
62 
63     //对数组进行排序
64 
65     NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
66 
67         NSLog(@"%@~%@",obj1,obj2); 
68 
69         //乱序
70 
71         if (arc4random_uniform(2) == 0) {
72 
73             return [obj2 compare:obj1]; //降序
74 
75         }
76 
77         else{
78 
79             return [obj1 compare:obj2]; //升序
80 
81         }
82 
83     }];
84 
85     NSLog(@"result=%@",result);
86 
87 }
88 
89  
原文地址:https://www.cnblogs.com/rglmuselily/p/5195264.html