The second chapter on the Computer Experiment report

Source: Internet
Author: User

1. Practice Title: 7-1

2. Problem Description: Use the binary lookup algorithm to find x in n non-descending integers, the subscript (0~n-1) where x is located, and the number of comparisons. If x does not exist, output-1 and number of comparisons.

3, algorithm Description: n elements are divided into roughly the same number of two halves, take A[mid] and x comparison. If X=a[mid], the x is found, the algorithm terminates, if X<A[MID], only the left half of the array a continues to look for X, if X>a[mid], then only the right half of a continues to search for X. Also, add a B statistic comparison number in the while statement.

4, the code is as follows:

1#include <iostream>2 using namespacestd;3 intBinarySearch (intA[],intLeftintRightintXint&b) { 4      while(left<=Right ) { 5b++;6         intMiddle = (left+right)/2; 7         if(x==A[middle]) { 8             returnMiddle;9         }Ten         if(x>A[middle]) { OneLeft=middle+1; A         } -         Else { -Right =middle-1; the         }  -     } -     return-1; - } + intMain () { -     intn,x,b=0; +Cin>>N; A     inta[ +]; at      for(intI=0; i<n;i++){ -Cin>>A[i]; -     } -Cin>>x; -     intIndex=binarysearch (A,0, N-1, x,b); -cout<<index<<endl<<b; in}

5. Time Complexity and space complexity: using the two-method search algorithm, the time complexity of searching for X is O (Logn), and the spatial complexity is a constant, which is independent of the value of variable N. So the spatial complexity is O (1).

6, Experience: to flexibly use the code learned, they are flexibly embedded in the problem to be solved. In solving the problem, we should consider the optimal solution, which is the least time complexity solution, which is advantageous to make the algorithm more convenient and the resources can be used rationally.

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.