对半搜索:
当表长是奇数:那就是中间元素作为分割点。
当表长是偶数:那就是中间两个元素的前一个作为分割点。
即(low + high) / 2 向下取整
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct{
int n;
int maxLength;
ElemType *element;
}ListSet;
int recursion_BinSearch(ListSet L, ElemType x, int low, int high){
if(low<=high){
int mid = (low+high)/2;
if(x<L.element[mid])
return recursion_BinSearch(L,x,low,mid-1);
else if(x>L.element[mid])
return recursion_BinSearch(L,x,mid+1,high);
else
return mid;
}
return -1;
}
int recursion_BinSearch(ListSet L, ElemType x){ //递归
int i = recursion_BinSearch(L,x,0,L.n-1);
return i;
}
int iteration_BinSearch(ListSet L, ElemType x){ //迭代
int mid,low = 0,high =L.n-1;
while(low<=high){
mid=(low+high)/2;
if(x<L.element[mid])
high = mid - 1;
else if(x>L.element[mid])
low = mid + 1;
else{
return mid;
}
}
return -1;
}
void Init(ListSet *L,int nSize){
int i ;
L->maxLength = nSize;
L->n = 0;
L->element = (ElemType*)malloc(sizeof(ElemType)*(L->maxLength));
for(i=0;i<L->maxLength;i++){
L->element[i] = i;
L->n++;
}
}
int main(){
int a;
ListSet L;
Init(&L,6);
a = recursion_BinSearch(L,9);
cout<<a<<endl;
a = iteration_BinSearch(L,9);
cout<<a<<endl;
return 0;
}