Binary search for finding the lowest and largest element in a sorted array than a given value?

hans

So, I was trying to implement the binary search algorithm (as generic as possible which can adapt to different cases). I searched for this on the internet, and some use, while (low != high) and some use, while (low <= high) and some other different condition which is very confusing.

Hence, I started writing the code for finding the first element which is greater than a given element. I wish to know if there is a more elegant solution than this?

Main code:

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <stack>
#include <queue>
#include <climits>
#include <set>
#include <cstring>

using namespace std;
int arr1[2000];
int n;
int main (void)
{
    int val1,val2;
    cin>>n;
    for (int i = 0; i < n; i++)
        cin>>arr1[i];
    sort(arr1,arr1+n); 
    cout<<"Enter the value for which next greater element than this value is to be found";   
    cin>>val1;
    cout<<"Enter the value for which the first element smaller than this value is to be found";
    cin>>val2;

    int ans1 = binarysearch1(val1);
    int ans2 = binarysearch2(val2);

    cout<<ans1<<"\n"<<ans2<<"\n";
    return 0;
}
int binarysearch1(int val)
{
    while (start <= end)
    {
        int mid = start + (end-start)/2;
        if (arr[mid] <= val && arr[mid+1] > val)
            return mid+1;
        else if (arr[mid] > val)
            end = mid-1;
        else
            start = mid+1;
    }
}

Similarly, for finding the first element which is smaller than the given element,

int binarysearch2(int val)
{

    while (start <= end)
    {
        int mid = start + (end-start)/2;
        if (arr[mid] >= val && arr[mid] < val)
            return mid+1;
        else if (arr[mid] > val)
            end = mid-1;
        else
            start = mid+1;
    }
}

I often get super confused when I have to modify binary search for such abstraction. Please let me know if there is simpler method for the same? Thanks!

AlexAlvarez

As you say, there are different ways to express the end condition for binary search and it completely depends on what your two limits mean. Let me explain mine, which I think it's quite simple to understand and it lets you modify it for other cases without thinking too much.

Let me call the two limits first and last. We want to find the first element greater than a certain x. The following invariant will hold all the time:

Every element past last is greater than x and every element before first is smaller or equal (the opposite case).

Notice that the invariant doesn't say anything about the interval [first, last]. The only valid initialization of the limits without further knowledge of the vector is first = 0 and last = last position of the vector. This satisfies the condition as there's nothing after last and nothing before first, so everything is right.

As the interval [first, last] is unknown, we will have to proceed until it's empty, updating the limits in consequence.

int get_first_greater(const std::vector<int>& v, int x)
{
  int first = 0, last = int(v.size()) - 1;
  while (first <= last)
  {
    int mid = (first + last) / 2;
    if (v[mid] > x)
      last = mid - 1;
    else
      first = mid + 1;
  }
  return last + 1 == v.size() ? -1 : last + 1;
}

As you can see, we only need two cases, so the code is very simple. At every check, we update the limits to always keep our invariant true.

When the loop ends, using the invariant we know that last + 1 is greater than x if it exists, so we only have to check if we're still inside our vector or not.

With this in mind, you can modify the binary search as you want. Let's change it to find the last smaller than x. We change the invariant:

Every element before first is smaller than x and every element after last is greater or equal than x.

With that, modifying the code is really easy:

int get_last_smaller(const std::vector<int>& v, int x)
{
  int first = 0, last = int(v.size()) - 1;
  while (first <= last)
  {
    int mid = (first + last) / 2;
    if (v[mid] >= x)
      last = mid - 1;
    else
      first = mid + 1;
  }
  return first - 1 < 0 ? -1 : first - 1;
}

Check that we only changed the operator (>= instead of >) and the return, using the same argument than before.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Finding the array with the lowest max value of element

From Dev

Finding smallest (or largest) k elements in a given balanced binary search tree

From Dev

finding the given element in the given array

From Dev

Binary search to find last element in sorted list that is less then specific value

From Dev

Return the insert position of an element into a sorted array with Binary Search Recursion

From Dev

Binary search tree largest value

From Dev

finding the index of last occurrence of an element in an array using binary search PHP

From Dev

finding the index of last occurrence of an element in an array using binary search PHP

From Dev

Finding the third largest even fraction in a given array

From Dev

Binary Search Like Algorithm to Find Change in Value in Sorted Array

From Dev

Finding Largest Element in an Array using JavaScript

From Dev

Finding largest element in a two dimensional array

From Dev

Find the largest number that is lesser than a given number in a sorted list

From Dev

Largest power of 2 no larger than a given value

From Dev

Finding the lines with the lowest value in their third column given grep results

From Dev

Finding the element with the lowest depth

From Dev

Finding the element with the lowest depth

From Dev

Fast searching for the lowest value greater than x in a sorted vector

From Dev

C++ finding the (largest) index of the largest element in an array

From Dev

Finding range index of a sorted array on a specific element

From Dev

Java, Finding Kth largest value from the array

From Dev

Binary Search a non-existing number in a sorted array, return a larger negative number than -1

From Dev

Finding the most frequent value in an array and then choosing the lowest value if there is a tie

From Dev

Find largest number of not sorted array without using linear and binary

From Dev

Find a number in sorted multidimentional array with binary search

From Dev

Insert sorted array into binary search tree

From Dev

binary search of sorted array in assembly language

From Dev

Insert sorted array into binary search tree

From Dev

Binary search inside sorted array in OCaml

Related Related

  1. 1

    Finding the array with the lowest max value of element

  2. 2

    Finding smallest (or largest) k elements in a given balanced binary search tree

  3. 3

    finding the given element in the given array

  4. 4

    Binary search to find last element in sorted list that is less then specific value

  5. 5

    Return the insert position of an element into a sorted array with Binary Search Recursion

  6. 6

    Binary search tree largest value

  7. 7

    finding the index of last occurrence of an element in an array using binary search PHP

  8. 8

    finding the index of last occurrence of an element in an array using binary search PHP

  9. 9

    Finding the third largest even fraction in a given array

  10. 10

    Binary Search Like Algorithm to Find Change in Value in Sorted Array

  11. 11

    Finding Largest Element in an Array using JavaScript

  12. 12

    Finding largest element in a two dimensional array

  13. 13

    Find the largest number that is lesser than a given number in a sorted list

  14. 14

    Largest power of 2 no larger than a given value

  15. 15

    Finding the lines with the lowest value in their third column given grep results

  16. 16

    Finding the element with the lowest depth

  17. 17

    Finding the element with the lowest depth

  18. 18

    Fast searching for the lowest value greater than x in a sorted vector

  19. 19

    C++ finding the (largest) index of the largest element in an array

  20. 20

    Finding range index of a sorted array on a specific element

  21. 21

    Java, Finding Kth largest value from the array

  22. 22

    Binary Search a non-existing number in a sorted array, return a larger negative number than -1

  23. 23

    Finding the most frequent value in an array and then choosing the lowest value if there is a tie

  24. 24

    Find largest number of not sorted array without using linear and binary

  25. 25

    Find a number in sorted multidimentional array with binary search

  26. 26

    Insert sorted array into binary search tree

  27. 27

    binary search of sorted array in assembly language

  28. 28

    Insert sorted array into binary search tree

  29. 29

    Binary search inside sorted array in OCaml

HotTag

Archive