Binary Search for the first element greater than target

Source: Internet
Author: User

We all know how to search through an array for an element whose value equals the target value, but how to search for the element that has value greater than the target value?

 

A participating ly elegant way of thinking about this problem is to think about doing a binary search over a transformed version of the array, where the array has been modified by applying the Function

f(x) = 1 if x > target       0 else

Now, the goal is to find the very first place that this function takes on the value 1. We can do that using a binary search as follows:

int low = 0; high = numElems;while (low != high) {    int mid = (low + high) / 2; // Or a fancy way to avoid int overflow    if (arr[mid] <= target) {        /* This index, and everything below it, must not be the first element         * greater than what we‘re looking for because this element is no greater         * than the element.         */        low = mid + 1.    }    else {        /* This element is at least as large as the element, so anything after it can‘t         * be the first element that‘s at least as large.         */        high = mid;    }}/* Now, low and high both point to the element in question. */

Reference: http://stackoverflow.com/questions/6553970/find-the-first-element-in-an-array-that-is-greater-than-the-target

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.