当数据量比较多的时候,使用系统自带的排序方式更高效sortedArrayUsingComparator,亲测当数据量为100时,系统的排序方法比冒泡法快10倍,数据量越大优势越明显;
当数据量比较少的时候使用冒泡法会快一点。
NSMutableArray * arr = [NSMutableArray new];
for (int i = 0; i < 100; i ++) {
int s = arc4random() % 1000;
[arr addObject:[NSString stringWithFormat:@"%d", s]];
}
//冒泡法排序
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < arr.count; i++) {
for (int j = 0; j < arr.count - i - 1; j++) {
if ([arr[j] integerValue] > [arr[j + 1] integerValue]) {
[arr exchangeObjectAtIndex:j withObjectAtIndex:(j + 1)];
}
}
}
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"time cost: %0.3f ms", (end - start)*1000);
CFAbsoluteTime start1 = CFAbsoluteTimeGetCurrent();
NSArray * sortArr = [arr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSInteger val1 = [obj1 integerValue];
NSInteger val2 = [obj2 integerValue];
//规定排序的规则
if (val1 > val2) {
return NSOrderedDescending;
}else {
return NSOrderedAscending;
}
}];
CFAbsoluteTime end1 = CFAbsoluteTimeGetCurrent();
NSLog(@"time cost: %0.3f ms\n, %@\n %@", (end1 - start1)*1000, arr, sortArr);
网友评论