1.快速排序
原理:
- 先从数列中取出一个数作为基数
- 分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边
- 再对左右区间重复第二步,直到各区间只有一个数;对两侧元素递归排序
- (NSArray *)quickSort:(NSMutableArray *)dataArray {
NSMutableArray *lessArray = [NSMutableArray array];
NSMutableArray *bigArray = [NSMutableArray array];
if (dataArray.count < ) {
return dataArray;
}
int midNumber = arc4random() % [dataArray count];
NSNumber *midValue = dataArray[midNumber];
[dataArray removeObjectAtIndex:midNumber];
for (NSNumber *number in dataArray) {
if (number < midValue) {
[lessArray addObject:number];
}else{
[bigArray addObject:number];
}
}
NSMutableArray *tempArray = [NSMutableArray array];
[tempArray addObjectsFromArray:[self quickSort:lessArray]];
[tempArray addObject:midValue];
[tempArray addObjectsFromArray:[self quickSort:bigArray]];
return tempArray;
}
优化:从并发执行入手提升速度,利用 dispatch_apply 快速迭代器加速循环速度
#pragma mark - 优化
- (NSArray *)optimizeQuickSort:(NSMutableArray *)dataArray {
NSMutableArray *lessArray = [NSMutableArray array];
NSMutableArray *bigArray = [NSMutableArray array];
if (dataArray.count < ) {
return dataArray;
}
int midNumber = arc4random() % [dataArray count];
NSNumber *midValue = dataArray[midNumber];
[dataArray removeObjectAtIndex:midNumber]; dispatch_queue_t concurrentQueue = dispatch_queue_create("com.cc.quickqeueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(dataArray.count, concurrentQueue, ^(size_t i) {
int index = (int)i;
NSNumber *num = dataArray[index];
if (num < midValue) {
[lessArray addObject:num];
}else{
[bigArray addObject:num];
}
});
NSMutableArray *tempArray = [NSMutableArray array];
[tempArray addObjectsFromArray:[self quickSort:lessArray]];
[tempArray addObject:midValue];
[tempArray addObjectsFromArray:[self quickSort:bigArray]];
return tempArray;
}
2.冒泡算法
越小的元素会经由交换慢慢"浮"到数列的顶端
#pragma mark - 冒泡
- (void)bubble:(NSMutableArray *)dataArray {
id temp;
for (int i = ; i < dataArray.count; i++) {
for (int j = ; j < dataArray.count; j++) {
if (dataArray[i] > dataArray[j]) {
temp = dataArray[i];
dataArray[i] = dataArray[j];
dataArray[j] = temp;
}
}
}
NSLog(@"%@",dataArray);
}