一
NSMutableArray *numbers = [NSMutableArray arrayWithObjects:@3, @1, @4, @1, @5, @9, @2, @6, @5, @3, @5, nil];
// 使用选项进行排序,这里我们不使用任何额外选项
NSMutableArray *sortedNumbers = [numbers sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return NSOrderedDescending;
} else if ([obj1 integerValue] < [obj2 integerValue]) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}];
二
- (void)onononon
{
NSMutableArray *array = [NSMutableArray arrayWithObjects:@3,@2,@9,@1,@6,@7,@4,@5,@8,@5,nil];
[self quickSortArray:array withLeftIndex:0 andRightIndex:(int)array.count - 1];
NSLog(@"排序后的数组===%@",array);
}
//快速排序
- (void)quickSortArray:(NSMutableArray *)array withLeftIndex:(NSInteger)leftIndex andRightIndex:(NSInteger)rightIndex{
if (leftIndex >= rightIndex) {//如果数组长度为0或1时返回
return ;
}
NSInteger i = leftIndex;
NSInteger j = rightIndex;
//记录比较基准数
NSInteger key = [array[i] integerValue];
while (i < j) {
/**** 首先从右边j开始查找比基准数小的值 ***/
while (i < j && [array[j] integerValue] >= key) {//如果比基准数大,继续查找
j--;
}
//如果比基准数小,则将查找到的小值调换到i的位置
array[i] = array[j];
/**** 当在右边查找到一个比基准数小的值时,就从i开始往后找比基准数大的值 ***/
while (i < j && [array[i] integerValue] <= key) {//如果比基准数小,继续查找
i++;
}
//如果比基准数大,则将查找到的大值调换到j的位置
array[j] = array[i];
}
//将基准数放到正确位置
array[i] = @(key);
/**** 递归排序 ***/
//排序基准数左边的
[self quickSortArray:array withLeftIndex:leftIndex andRightIndex:i - 1];
//排序基准数右边的
[self quickSortArray:array withLeftIndex:i + 1 andRightIndex:rightIndex];
}
NSArray * array = @[@"20",@"80",@"99",@"86",@"68",@"39",@"69",@"23",@"79",@"97"];
float sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
float avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
float max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
float min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
网友评论