折半查找利用了记录按关键码有序的特点,其基本思想是:在有序表中,取中间记录作为比较对象,若给定值与中间记录的关键码相等,则查找成功;若给定值小于中间记录的关键码,则在中间记录的作伴去继续查找,反之在右半区查找。不断重复以上过程,直到查找成功。因此折半查找可以用递归来实现。算法复杂度O(logn).
//
// main.cpp
// BinSearch
//
// Created by sanyinchen on 14-9-2.
// Copyright (c) 2014年 sanyinchen. All rights reserved.
//
#include <iostream>
using namespace std;
int a[5]={1,2,3,4,5};
int p=1;
int binSearch(int *r,int low,int high,int k)
{
int mid=(low+high)/2;
if(low>high)
return mid;
if(k<r[mid])
return binSearch(r, low, mid-1, k);
else
return binSearch(r, mid+1, high, k);
}
void binSearch2(int *r,int low,int high,int k)
{
int mid=0;
while(low>high)
{
mid=(low+high)/2;
if(k<r[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
cout<< r[mid];
}
int main(int argc, const char * argv[])
{
cout<<binSearch(a,0,4,2)<<endl;
binSearch2(a,0,4,2);
return 0;
}