Chapter II work practice report

1, practice topics :

            Binary search

2. Description of the problem:

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 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

 

3, the algorithm description

A first write function bisearch dichotomy () with l, r represent each array to find the leftmost and rightmost address, intermediate address, and represents a number in a lookup by comparing the size of m, if a [m] is equal to logarithmic search is stopped, otherwise the cycle call the function again, when a [m]> x, then r = m-1; when a [m] <r, then l = m + 1; until found or no end- So far, the number represented by t, t called once each incremented by one, calculating the number of comparisons.

 

code:

#include <iostream>

using namespace std;

int bisearch(int a[],int l,int r,int x, int &t )

{

    if(l>r) return -1;

   

    int m=(l+r)/2;

    t++;

    if(a[m]==x) return m;

    if(a[m]>x) return bisearch(a,l,m-1,x,t);

    if(a[m]<x) return bisearch(a,m+1,r,x,t);

}

int main () {

    int n,x,t=0;

    cin>>n;

    int a[n];

    for(int i=0;i<n;i++)

    {

        cin>>a[i];

    }

    cin>>x;

    cout<<bisearch(a,0,n-1,x,t)<<endl;

    cout<<t<<endl;

    return 0;

}

4. The time and complexity of the spatial analysis algorithm

Each algorithm calls a function, the array size need to be searched by half, in the worst case, be called O (log n) time. And functions execute in O (1) time, the time complexity of the algorithm is O (log n)

5 experiences

To use will be called recursively, circulation and other algorithms, understand the principles of arithmetic topics, the subject of a number of multi-cycle thinking recursive call, simplify the code as much as possible, to analyze the time complexity, more thinking of writing code is the optimal solution, there are two points to consider are sometimes thought of Boolean functions.

Guess you like

Origin www.cnblogs.com/paipaihh/p/11575326.html