二分查找法
时间算法度: Θ ( l g n ) Θ(lgn) Θ(lgn)
该算法主旨:
每次循环/递归迭代查找,都将序列分成两半,再根据判断选择下一个将要分成两半的子序列。直到找到我们需要的数字,或没有找到则返回
−
1
-1
−1。
伪代码:
/* ——————————————————————————————————————————————————
* 二分查找法有两种方法,一个是用循环,一个是利用递归
* —————————————————————————————————————————————————— */
// 循环方法:
Binary-Search-Cycle(A, front, back, Number)
1 middle = (front + back) / 2
2 while front <= back
3 if Number < A[middle]
4 back = middle - 1
5 middle = (front + back) / 2
6 else if Number > A[middle]
7 front = middle + 1
8 middle = (front + back) / 2
9 else
10 return middle11 return -1
// 递归方法:
Binary-Search-Recursion(A, front, back, Number)
1 if front >= back
2 return -1
3 middle = (front + back) / 2
4 if A[middle] == Number
5 return middle
6 else if Number < A[middle]
7 Binary-Search-Recursion(A, front, middle - 1, Number)
8 else if Number > A[middle]
9 Binary-Search-Recursion(A, middle + 1, back, Number)
C++代码:
// 循环方法:
int Binary_Search_Cycle(int *A, int front, int back, int Number)
{
int middle = (front + back) / 2;
while (front <= back)
{
if (Number < A[middle])
{
back = middle - 1;
middle = (front + back) / 2;
}
else if (Number > A[middle])
{
front = middle + 1;
middle = (front + back) / 2;
}
else
return middle;
}
return -1;
}
// 递归方法:
int Binary_Search_Recursion(int *A, int front, int back, int Number)
{
if (front > back)
return -1;
int middle = (front + back) / 2;
if (A[middle] == Number)
return middle;
else if (Number < A[middle])
Binary_Search_Recursion(A, front, middle - 1, Number);
else
Binary_Search_Recursion(A, middle + 1, back, Number);
}
测试代码:
#include <iostream>
constexpr int N = 5;
// 循环二分查找法声明
int Binary_Search_Cycle(int *A, int front, int back, int Number);
// 递归二分查找法声明
int Binary_Search_Recursion(int *A, int front, int back, int Number);
int main(void)
{
int A[N]{ 1, 2, 3, 4, 5 };
// 测试循环方法的二分查找法:
for (int i = 0; i < 5; i++)
std::cout << Binary_Search_Cycle(A, 0, N - 1, i + 1) << " ";
std::cout << Binary_Search_Cycle(A, 0, N - 1, 10) << std::endl;
// 测试递归方法的二分查找法:
for (int i = 0; i < 5; i++)
std::cout << Binary_Search_Recursion(A, 0, N - 1, i + 1) << " ";
std::cout << Binary_Search_Recursion(A, 0, N - 1, 10) << std::endl;
return 0;
}
// 循环二分查找法定义
int Binary_Search_Cycle(int *A, int front, int back, int Number)
{
int middle = (front + back) / 2;
while (front <= back)
{
if (Number < A[middle])
{
back = middle - 1;
middle = (front + back) / 2;
}
else if (Number > A[middle])
{
front = middle + 1;
middle = (front + back) / 2;
}
else
return middle;
}
return -1;
}
// 递归二分查找法定义
int Binary_Search_Recursion(int *A, int front, int back, int Number)
{
if (front > back)
return -1;
int middle = (front + back) / 2;
if (A[middle] == Number)
return middle;
else if (Number < A[middle])
Binary_Search_Recursion(A, front, middle - 1, Number);
else
Binary_Search_Recursion(A, middle + 1, back, Number);
}
/* ——————————————————————————————————————————————————
* 输出结果:
* 0 1 2 3 4 -1
* 0 1 2 3 4 -1
* —————————————————————————————————————————————————— */