简体   繁体   中英

Making use of binary search algorithm

I'm more interested in the thought process than in the code itself. I'm supposed to find the number of v[i] components in a sorted array such that x < v[i] < y , where x and y are sent as input from the keyboard. I'm supposed to solve this efficiently using a modified binary search instead of a regular search through the vector.

My problem is that I can't visualize how to implement a binary search in this case, the method just doesn't seem fit to me.

Any thoughts ?

You could do a binary search in the array for x and y . Then you could subtract the index of x from the index of y to get how many items are between them.

You'd actually have to subtract 1 from that result since you are using strictly less-than.

For example, say you have an array:

[3, 6, 8, 10, 14, 39, 41, 100]

Let x=8 and y = 39.

The index of x is 2 and the index of y is 5.

5-2 = 3

3-1 = 2

If x and y are allowed to be values that are not contained in your array, you can still follow the same approach. Search for x and if it is not found, use the index of the element that is just larger than x. Likewise for the index of the element that is just smaller than y .

Supposing the original array v is sorted, just follow those steps:

  1. Use binary search to locate value x in the array - if it's not there (the lower and upper bounds in binary search meet), get the index of closest higher value
  2. Do the same for the y value, get the index of closest lower value if it's not this time
  3. Find out how many items are in between (by subtracting indices and adding 1)

Here's a great article if you're interested: Binary Search

Depending on the values of x and y , if they're the lower and upper limits respectively of numbers within the array, it's as simple as applying a general BS algorithm with those limits in place rather than the general first and last element of the array.

Drawing it up on paper will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM