常用排序(oc实现)

常用排序(oc实现)


冒泡排序

//由小到大 排序
//NSNumber 中用的int类型
+(void)BubbleSort:(NSMutableArray<NSNumber*> *)arr
{
NSLog(@" 冒泡排序前 :%@  ",arr);
for (int i = 0; i < arr.count; i++) {
    for (int j = 0; j < arr.count - i - 1;j++) {
        if ([arr[j+1]integerValue] < [arr[j] integerValue]) {
            int temp = [arr[j] integerValue];
            arr[j] = arr[j + 1];
            arr[j + 1] = [NSNumber numberWithInt:temp];
        }
    }
}
NSLog(@"冒泡排序后:%@",arr);
}

快速排序

//由小到大 排序
//NSNumber 中用的 long long 类型
+(void)quickSort:(NSMutableArray<NSNumber*> *)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<NSNumber*> *)arr leftIndex:(int)left rightIndex:(int)right
{
long long tempValue = [arr[left] longLongValue];
while (left < right) {
    while (left < right && tempValue <= [arr[right] longLongValue]) {
        right --;
    }
    if (left < right) {
        arr[left] = arr[right];
    }
    
    while (left < right && [arr[left] longLongValue] <= tempValue) {
        left ++;
    }
    if (left < right) {
        arr[right] = arr[left];
    }
}
arr[left] = [NSNumber numberWithLongLong:tempValue];
return left;
}

选择排序

//由小到大 排序
//NSNumber 中用的 int 类型
+(void)SelectionSort:(NSMutableArray<NSNumber*> *)arr
{
for (int i = 0; i < arr.count; i ++) {
    for (int j = i + 1; j < arr.count; j ++) {
        if ([arr[i] integerValue] > [arr[j] integerValue]) {
            int temp = [arr[i] integerValue];
            arr[i] = arr[j];
            arr[j] = [NSNumber numberWithInt:temp];
        }
    }
}

NSLog(@"选择排序后:%@",arr);
}

插入排序

//由小到大 排序
//NSNumber 中用的 int 类型
+(void)InsertSort:(NSMutableArray<NSNumber*> *)arr
{
for (int i = 1; i < arr.count; i ++) {
    int temp = [arr[i] integerValue];
    
    for (int j = i - 1; j >= 0 && temp < [arr[j] integerValue]; j --) {
        arr[j + 1] = arr[j];
        arr[j] = [NSNumber numberWithInt:temp];
    }
    
    
}
NSLog(@"插入排序后:%@",arr);
}
posted @ 2016-03-03 11:19  孙焱焱  阅读(418)  评论(0编辑  收藏  举报