冒泡排序 快速排序 选择排序 插入排序

来源:互联网 发布:java连接池原理 编辑:程序博客网 时间:2024/06/06 16:59

//冒泡排序


-(void)bubbleSort{

    NSMutableArray *dataArray = [[NSMutableArrayalloc]initWithArray:_valueArray];

    for (int i =0; i<dataArray.count-1; i++) {

        for (int j =0; j<dataArray.count-i-1; j++) {

            if ([dataArray[j]intValue] > [dataArray[j+1]intValue]) {

                int temp = [dataArray[j]intValue];

                dataArray[j] = dataArray[j+1];

                dataArray[j+1] = [NSStringstringWithFormat:@"%d",temp];

            }

        }

    }

    NSLog(@"冒泡排序%@",dataArray);

}


//快速排序

-(void)quickSort{

    NSMutableArray *dataArray = [[NSMutableArrayalloc]initWithArray:_valueArray];

    [selfquickSort:dataArray leftIndex:0rightIndex:dataArray.count -1];

}

- (NSInteger)getMiddleIndex:(NSMutableArray *)arr leftIndex:(NSInteger)left rightIndex:(NSInteger)right

{

    NSInteger tempValue = [arr[left]integerValue];

    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] = [NSNumbernumberWithInteger:tempValue];

    NSLog(@"快速排序%@",arr);

    return left;

}

- (void)quickSort:(NSMutableArray *)arr leftIndex:(NSInteger)left rightIndex:(NSInteger)right

{

    if (left < right) {

        NSInteger temp = [selfgetMiddleIndex:arr leftIndex:left rightIndex:right];

        [selfquickSort:arr leftIndex:leftrightIndex:temp - 1];

        [selfquickSort:arr leftIndex:temp +1 rightIndex:right];

    }

}



//选择排序

-(void)selectionSort{

    NSMutableArray *dataArray = [[NSMutableArrayalloc]initWithArray:_valueArray];

    for (int i =0; i < dataArray.count; i ++) {

        for (int j = i +1; j < dataArray.count; j ++) {

            if ([dataArray[i]integerValue] > [dataArray[j]integerValue]) {

                NSInteger temp = [dataArray[i]integerValue];

                dataArray[i] = dataArray[j];

                dataArray[j] = [NSNumbernumberWithInteger:temp];

            }

        }

    }

    NSLog(@"选择排序%@",dataArray);

}



//插入排序

-(void)insertionSort{

    NSMutableArray *dataArray = [[NSMutableArrayalloc]initWithArray:_valueArray];

    for (int i =1; i < dataArray.count; i ++) {

        NSInteger temp = [dataArray[i]integerValue];

        for (int j = i -1; j >= 0 && temp < [dataArray[j]integerValue]; j --) {

            dataArray[j + 1] = dataArray[j];

            dataArray[j] = [NSNumbernumberWithInteger:temp];

        }

    }

    NSLog(@"%@",dataArray);

}



0 0
原创粉丝点击