Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Binary Search for Left and Right Boundary Detection

Tech 3

When calculating the midpoint in binary search, two approach are commonly used:

  1. mid = left + (right - left) / 2 - This method prevents integer overflow by first cmoputing the interval length
  2. mid = (left + right) / 2 - This simpler form may cause overflow with large values

The first approach is recommended for safety.

For boundary detection, we use inclusive boundss with additional range checks:

Left Boundary Search Implementation:

class BoundaryFinder {
    int findLeftEdge(int[] data, int key) {
        int low = 0;
        int high = data.length - 1;
        
        while (low <= high) {
            int center = low + (high - low) / 2;
            
            if (data[center] == key) {
                high = center - 1;
            } else if (data[center] < key) {
                low = center + 1;
            } else {
                high = center - 1;
            }
        }
        
        if (low >= data.length || data[low] != key) {
            return -1;
        }
        
        return low;
    }
}

Right Boundary Search Implementation:

class BoundaryFinder {
    int findRightEdge(int[] data, int key) {
        int low = 0;
        int high = data.length - 1;
        
        while (low <= high) {
            int center = low + (high - low) / 2;
            
            if (data[center] == key) {
                low = center + 1;
            } else if (data[center] < key) {
                low = center + 1;
            } else {
                high = center - 1;
            }
        }
        
        if (high < 0 || data[high] != key) {
            return -1;
        }
        
        return high;
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.