继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

iOS OC实现二分查找和快速排序

ZKReadStone
关注TA
已关注
手记 52
粉丝 32
获赞 322
//二分查找   默认查找有序数组
- (NSInteger)searchTarget:(NSInteger)target fromArr:(NSArray *)arr
{
    if (arr.count < 1) {
        return -1;
    }
    NSInteger start,mid,end;
    start = 0;
    mid = 0 ;
    end = arr.count-1;
    while (start < end-1) {//就剩两个数的时候  start = end - 1;这个条件跳出
        mid = start + (end - start)/2;
        if ([arr[mid] integerValue] > target) {
            end = mid;
        }else{
            start = mid;
        }
    }
    if (target == [arr[start] integerValue]) {
        return start;
    }
    if (target == [arr[end] integerValue]) {
        return end;
    }
    return -1;
}
//快速排序
- (void)sortArr:(NSMutableArray *)arr left:(NSInteger)left right:(NSInteger)right
{//@[@3,@4,@1,@6,@5,@2,@9,@7,@8]
    if (left >= right) {//如果数组长度为0或1时返回  递归调用的必备跳出
        return ;
    }
    NSInteger i,j,base;
    i = left;
    j = right;
    base = [arr[left] integerValue];
    while(i < j){
        while([arr[j] integerValue] >= base&&i<j){
            j--;
        }
        arr[i] = arr[j];
        while ([arr[i] integerValue] <= base&&i<j) {
            i++;
        }
        arr[j] = arr[i];
      
    }
    arr[i] = @(base);
    [self sortArr:arr left:left right:i-1];
    [self sortArr:arr left:i+1 right:right];
}

  NSMutableArray *array = @[@3,@4,@1,@6,@5,@2,@9,@7,@8].mutableCopy;
    [self sortArr:array left:0 right:array.count-1];
   
    NSArray *arr = @[@1,@3,@4,@6,@7,@8,@9];
    NSArray *arr0 = @[@2,@3,@5,@7,@8,@9];
    NSArray *arr1 = @[@2,@3,@7,@7,@8,@9];

    NSInteger i = [self searchTarget:7 fromArr:arr];
    NSInteger j = [self searchTarget:7 fromArr:arr0];
    NSInteger k = [self searchTarget:7 fromArr:arr1];
    NSLog(@"---------%ld\n ===========%ld \n +++++++++++%ld",i,j,k);
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP