1. Topic :
Value for n (1 <= n <= 1000), n non-descending order of an integer and the number of x to find, using the binary search algorithm to find the x, output x where the subscripts (0 ~ n-1) and the number of comparisons . If x does not exist, the output 1 and the number of comparisons.
Input formats:
The input common three lines: The first line is the value of n; n is an integer second line; the third line is the x value.
Output formats:
Where the subscript x output (0 ~ n-1) and the number of comparisons. If x does not exist, the output 1 and the number of comparisons.
Sample input:
4
1 2 3 4
1
Sample output:
0 2
2.问题描述:用二分查找在一个有序数组中找一个数,并求出比较次数。
3.算法描述:
使用二分查找算法,每进行一次比较判断前计数加一。
代码如下:
#include <iostream>
using namespace std;
int BinarySearch(int a[],int x,int n){
int left = 0;
int right =n-1;
int count =0;
while(left <= right){
int middle = (left + right)/2;
count++;
if(x== a[middle]){
cout<<middle<<endl;
cout<<count;
return middle;
}
if(x>a[middle]){
left =middle + 1;
}
else {
right = middle -1;
}
}
cout<<"-1"<<endl;
cout<<count;
return -1;
}
int main () {
int n;
cin>>n;
int *a=new int[n];
for(int i=0; i<n;i++){
cin>>a[i];
}
int x;
cin>>x;
BinarySearch(a,x,n);
return 0;
}
4.算法时间复杂度及空间复杂度
原本规模为n,运用了二分法,每次都除以二,即o(logN),
空间复杂度为o(1)。
5.心得体会(对本次实践收获及疑惑进行总结)
(1.巩固了二分查找法,学会了在二分查找算法里面计数。
(2.也解决了对“在函数里面输出结果然而还要用return”的问题:因为若不用return,
循环不得停止,则也没办法退出循环输出查找不到的情况。