最近
闲来无事,看到以前写的demo,做个记录,以下是比较简单的几种排序算法:
NSMutableArray * arr = [[NSMutableArray alloc] initWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:9],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:6],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:2],
nil];
NSLog(@"排序前%@",arr);
int count = 0;
// NSArray的排序法
// [arr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// if ([(NSNumber *)obj1 intValue] < [(NSNumber *)obj2 intValue]) {
// return NSOrderedSame;
// }
// return NSOrderedDescending;
// }];
// 冒泡算法
for (int i = 0; i < arr.count; i ++) {
for (int j = 0; j < arr.count - i - 1; j ++) {
count ++;
if ([arr[j + 1] intValue] > [arr[j] intValue]) {
NSNumber * temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 选择排序
// for (int i = 0; i < arr.count; i ++) {
// for (int j = i + 1; j < arr.count; j ++) {
// count ++;
// if ([arr[i] intValue] > [arr[j] intValue]) {
// NSNumber * temp = arr[i];
// arr[i] = arr[j];
// arr[j] = temp;
// }
// }
// }
// 插入法
// for (int i = 1; i < arr.count; i ++) {
// int temp = [arr[i] intValue];
// for (int j = i - 1; j >= 0; j --) {
// count ++;
// if ([arr[j] intValue] > temp) {
// arr[j + 1] = arr[j];
// arr[j] = [NSNumber numberWithInt:temp];
// }
// }
// }
// 快速排序
// [self quickSort:arr leftIndex:0 rightIndex:5];
NSLog(@"一共循环了%d次",count);
NSLog(@"排序后%@",arr);
- (void)quickSort:(NSMutableArray *)arr leftIndex:(int)left rightIndex:(int)right
{
if (left < right) {
int temp = [self getMiddleIndex:arr leftIndex:left rightIndex:right];
[self quickSort:arr leftIndex:left rightIndex:temp - 1];
[self quickSort:arr leftIndex:temp + 1 rightIndex:right];
}
}
- (int)getMiddleIndex:(NSMutableArray *)arr leftIndex:(int)left rightIndex:(int)right
{
int tempValue = [arr[left] intValue];
while (left < right) {
while (left < right && tempValue <= [arr[right] integerValue]) {
right --;
}
if (left < right) {
arr[left] = arr[right];
}
while (left < right && [arr[left] integerValue] <= tempValue) {
left ++;
}
if (left < right) {
arr[right] = arr[left];
}
}
arr[left] = [NSNumber numberWithInt:tempValue];
return left;
}
感谢百科...