The second chapter on the Computer Experiment report

Source: Internet
Author: User

1. Practice title: Two-point search

2. Problem Description: Enter n values (1<=n<=1000), n non-descending integers, and x to find, use binary lookup algorithm to find x, Output x subscript (0~n-1), and number of comparisons. If x does not exist, output-1 and number of comparisons.

3. Algorithm Description:

#include <iostream>
using namespace Std;
int count=0;
int binarysearch (int a[],int left, int. right, int x) {
count++;
if (left==right&&a[left]!=x) {
return-1;
}
else{
int mid = (left+right)/2;
if (a[mid]==x) {
return mid;
}

if (X>mid) {
return BinarySearch (A,MID+1,RIGHT,X);
}
else{
return BinarySearch (A,LEFT,MID-1,X);
}
}
}
int a[1005];
int main () {
int x,n;
cin>>n;
for (int i=0;i<n;i++) {
cin>>a[i];
}
cin>>x;
int ans;
Ans = BinarySearch (a,0,n-1,x);
cout<<ans<<endl<<count;
return 0;
}

4, algorithm time and spatial complexity analysis (to have the analysis process)

Because a binary lookup excludes half of the unsuitable values each time, the case for n elements:
One minute left: N/2
Two second points left: N/2/2 = N/4
。。。
M-second two points left: n/(2^m)
In the worst case, the result is excluded until the last value is left, which is thought to be
n/(2^m) = 1;
2^m=n;
So the complexity of time is: log2 (n)
Because the auxiliary space is constant level, the spatial complexity is O (1);

5, experience (to this practice harvest and doubts to summarize)

This practice let me more clearly understand the two-point search algorithm and the idea of division, before the binary search code implementation is also confused, after this practice, there is a clear concept. Two-point search through continuous binary reduce the number of comparisons, has been relatively good time complexity, this is the harvest in this practice. In this paper, the realization of recursive code has been solved after this practice.

The second chapter on the Computer Experiment report

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.