OC语言的一些基础算法

1:逆序查找

-(void)reverseSequenceLookUpWithArray:(NSMutableArray *)array{
    
    for (int min = 0, max = (int)array.count-1; min < max; min++,max--) {
        NSString *temp;
        temp = array[min];
        array[min] = array[max];
        array[max] = temp;
    }
    
}

注意:比较大小时注意把数组里面的对象转换为基本数据类型再进行比较

2:选择排序

-(void)selectSortWithArray:(NSMutableArray *)array{
    for (int i = 0; i < array.count - 1; i++) {
        for (int j = i+1; j < array.count; j++) {
            int a = [array[i] intValue];
            int b = [array[j] intValue];
            NSString * temp;
            if (b < a) {

                temp = array[j];
                array[j] = array[i];
                array[i] = temp;
                
            }
        }
    }
}

3:冒泡排序

-(void)bubbleSortWithArray:(NSMutableArray *)array{
    for (int i = 0; i < array.count - 1; i++) {
        for (int j = 0; j < array.count - 1 - i; j++) {
            int a = [array[j] intValue];
            int b = [array[j + 1] intValue];
            NSString * temp;
            if (b < a) {
                temp = array[j + 1];
                array[j + 1] = array[j];
                array[j] = temp;
        }
    }
    
 }
}

4:折半查找(前提数组必须是有序的)

-(void)binarySearchWithArray:(NSMutableArray *)array withNumber:(int)num{
    int min = 0;
    int max = (int)(array.count - 1);
    int mid = (min + max)/2;
    while (min <= max) {
        for (int i = 0; i < array.count - 1; i++) {
            if (num < [array[mid] intValue]) {
                max = mid - 1;
            }else if(num > [array[mid] intValue]){
                min = mid + 1;
            }else{
                id a = array[mid];
                NSLog(@"-----%@",a);
                return;
            }
            mid = (min + max)/2;
        }
    }
    NSLog(@"没有匹配项");
    return;

}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页