# 查找算法系列之简单查找：顺序查找、二分查找、分块查找

### 1.顺序查找

template<class T>
int OrderSearch(T *x, int N, T keyWord)
{
for(int i = 0; i < N; i++)
{
if(x[i] == keyWord)
return i;
}
return -1;
}

### 2.二分查找

template<class T>
int binarySearch(T *x, int low, int high, T keyword)//递归
{
if(low > high)
return -1;
int mid = (low + high)/2;
if(x[mid] == keyword)
return mid;
if(x[mid] < keyword)
return binarySearch(x, mid+1, high);
if(x[mid] > keyword)
return binarySearch(x, low, mid-1);
}

template<class T>
int binarySearch(T *x, int N, T keyword)//无递归
{
int low = 0, high = N-1,mid;
while(low <= high)
{
mid = (low + high)/2;
if(x[mid] == keyword)
return mid;
else
if(x[mid] < keyword)
low = mid + 1;
else
high = mid -1;

}
return -1;
}

### 3.分块查找

//分块查找
template<class T>//索引表
struct INDEXTable
{
T key;
};

template<class T>  IndexOrderSearch(INDEXTable<T> *indexTable,T *x, int N, int m, T keyword)// indexTable为索引表,x为原数组,N为数组大小，m为块大小
{
int L = (N+m-1)/m;
int i = 0;
while(i < L && indexTable[i].key < keyword)
i++;
if(i == L)
return -1;
else
{
if(x[j] == keyword)
return j;
}
return -1;
}