查收算法之折半(二分)

        折半查找法也称为二分查找法。它的基本思想是,将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法终止。如 果x<a[n/2],则我们只要在数组a的左半部继续搜索x(这里假设数组元素呈升序排列)。如果x>a[n/2],则我们只要在数组a的右 半部继续搜索x。

        假设其数组长度为n,其算法复杂度为o(log(n))。

        伪代码写一下:

        findYou(startIndex,countIndex)

        {

                  //计算出中间位置

                  mid = (startIndex + countIndex)/2;

                  if(startIndex > countIndex - 1)

                  {

                        return -1;

                  }

          if(searchScaleArray[min] == searchKey)

          {

                return min;

          }

          else

          {

               if(searchScaleArray[min] < searchKey)

               {

                      //递归

                      findYou(min + 1,countIndex);

               }

               else

              {

                      //递归

                      findYou(startIndex,mid - 1);

               }

          }

        }


        oc 代码实现:

        

#import "ViewController.h"

@interface ViewController ()
{
    NSInteger searchKey;
    NSInteger searchCount;
}

@property (nonatomic, strong) NSMutableArray *findArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    searchKey = 0;
    searchCount = 0;
    
    //保证是有序的
    _findArray = [NSMutableArray arrayWithObjects:@0,@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12, nil];
    
    [self findYouWithStartIndex:0 countIndex:_findArray.count];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark - 折半查找
- (NSInteger) findYouWithStartIndex:(NSInteger) startIndex  countIndex:(NSInteger) countIndex
{
    //获取中间值
    NSInteger mid = (startIndex + countIndex)/2;
    
    searchCount ++;
    
    NSLog(@"计算次数-------%ld",(long)searchCount);
    
    if (startIndex > countIndex - 1)
    {
        NSLog(@"-----\\%d\\------",-1);
        return -1;
    }
    
    if ([_findArray[mid] integerValue] == searchKey)
    {
        NSLog(@"-----%ld------",(long)mid);
        return mid;
    }
    else
    {
        if ([_findArray[mid] integerValue] < searchKey)
        {
            return [self findYouWithStartIndex:mid + 1 countIndex:countIndex];
        }
        else
        {
            return [self findYouWithStartIndex:startIndex countIndex:mid - 1];
        }
    }
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值