binary search 1

1. Inspection points

1. Binary search can be used not only in ordered sequences, but also in unordered sequences, as long as each search is satisfied, the search range will be reduced by half.

2. Pay attention to the initial conditions of the loop, the boundary value, and the processing of dividing points to ensure that the loop will not fail to terminate.

3. Classical writing of dividing point: (p+r)/2, safe writing: r-(rp)/2 or p+(rp)/2

 

2. Local minima problem

  Local minimum: in an unordered sequence, and any two adjacent elements are not equal, satisfy arr[i]<arr[i+1] and arr[i]<arr[i-1] The element arr[i] is called a local minimum.

  How to find:

    1. Return when arr is empty or length is 1.

    2. Determine the situation of the two ends

      Returns immediately if one of the endpoint values ​​is a local minimum.

    3. Neither side of the endpoint is a local minimum, as follows, discuss the midpoint mid.

      

    4. The case of the middle point

      1. When it belongs to case 2, return mid directly.

      2. Otherwise, such as the two sides of 3 and the left side of 4, there is a local minimum ratio, because the adjacent elements are different, taking the left side of 4 as an example,

      On the left side of mid, once there is a rising point, this point is the local minimum, otherwise if it keeps descending to the left, arr[1] is the local minimum.

      3. Case 5 not shown refers to case 4.

      

 

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325115348&siteId=291194637