插入排序

- (void)insertSort
{
    NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:@3,@4,@6,@2,@9,@7,@8, nil];
    for (int i = 0; i<dataArray.count-1; i++) {
        NSInteger j = i+1;
        while (j>=1 && [dataArray[j-1]integerValue]<[dataArray[j]integerValue]) {
            id obj = dataArray[j];
            [dataArray replaceObjectAtIndex:j withObject:dataArray[j-1]];
            [dataArray replaceObjectAtIndex:j-1 withObject:obj];
            j--;
            [AlgorithmSort printArray:dataArray];
        }
    }
    [AlgorithmSort printArray:dataArray];
    
}

- (void)kInserSort:(NSMutableArray *)array{
    array = [NSMutableArray arrayWithObjects:@3,@4,@6,@2,@9,@7,@8, nil];
    for (int i = 0; i < array.count; i++) {
        NSNumber *temp = array[i];
        int j = i-1;
        while (j >= 0 && [array[j] compare:temp] == NSOrderedDescending) {
            [array replaceObjectAtIndex:j+1 withObject:array[j]];
            j--;
        }
        [array replaceObjectAtIndex:j+1 withObject:temp];
        NSLog(@"插入排序排序中:%@",array);
    }
}



+ (void)printArray:(NSArray *)array
{
    for(NSNumber *number in array) {
        printf("%d ",[number intValue]);
    }
    
    printf("\n");
}

posted @ 2018-08-14 11:19  路在脚下,  阅读(62)  评论(0编辑  收藏  举报