一、NSArray封装的排序算法
1、
NSComparator cmptr = ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *array = [sortArray sortedArrayUsingComparator:cmptr];
2、
NSInteger customSort(id obj1, id obj2,void* context) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}
NSArray *array = [sortArray sortedArrayUsingFunction:customSort context:nil];
二、经典排序算法
1、冒泡算法
- (void)bubbleSort(NSArray *arr) {
int i, j, k;
for(i = 0 ; i < arr.count - 1 ; i++) {
// j每循环一次,都把最大的一个数据冒出气泡,即可不再处理
for(j = 0 ; j < arr.count - i ; j++) {
if(arr[j] > arr[j+1]) {
k = arr[j];
arr[j] = arr[j+1];
arr[j+1] = k;
}
}
}
}
2、插入排序
- (void)insertSort(NSArray *arr) {
int j, i, m;
for(j = 1; j < arr.count; j++) {
m = a[j];
for(i = j - 1; i >= 0; i--){
if(a[i] < m)
break;
else
a[i + 1] = a[i];
}
a[i+1] = m;
}
}