Binary search if array contains duplicates

binary search with duplicates
find duplicate elements in array in c
check if array has duplicate values javascript
binary search algorithm with duplicates
c++ binary search duplicates
find the duplicate number binary search
binary search with duplicates leetcode
given an array of integers, find if the array contains any duplicates

Hi,

what is the index of the search key if we search for 24 in the following array using binary search.

array = [10,20,21,24,24,24,24,24,30,40,45]

I have a doubt regarding binary search that how does it works if a array has duplicate values.Can anybody clarify...

The array you proposed has the target value in the middle index, and in the most efficient implementations will return this value before the first level of recursion. This implementation would return '5' (the middle index).

To understand the algorithm, just step through the code in a debugger.

public class BinarySearch {
    public static int binarySearch(int[] array, int value, int left, int right) {
          if (left > right)
                return -1;
          int middle = left + (right-left) / 2;
          if (array[middle] == value)
                return middle;
          else if (array[middle] > value)
                return binarySearch(array, value, left, middle - 1);
          else
                return binarySearch(array, value, middle + 1, right);           
    }

    public static void main(String[] args) {
        int[] data = new int[] {10,20,21,24,24,24,24,24,30,40,45};

        System.out.println(binarySearch(data, 24, 0, data.length - 1));
    }
}

Result of java.util.Arrays.binarySearch() when input contains , From the documentation: Searches a range of the specified array of ints for the specified value using the binary search algorithm. The range� Well, if you actually do have a sorted array, you can do a binary search until you find one of the indexes you're looking for, and from there, the rest should be easy to find since they're all next to each-other. once you've found your first one, than you go find all the instances before it, and then all the instances after it.

As pointed out by @Pleepleus it will return the index 5 from the first level of recursion itself. However I would like to point out few things about binary search :

  1. Instead of using mid = (left + right)/2 , use mid = left + (right-left)/2
  2. If you want to search for lower_bound or upper_bound of an element use the following algorithms:

    binLowerBound(a, lo, hi, x)
      if (lo > hi)
        return lo;
    
      mid = lo +  (hi - lo) / 2;
      if (a[mid] == x)
        return binLowerBound(a, lo, mid-1, x);
      else if (a[mid] > x)
        return binLowerBound(a, lo, mid-1, x);
      else
        return binLowerBound(a, mid+1, hi, x);
    
    binHigherBound(a, lo, hi, x)
      if (lo > hi)
        return lo;
      mid = lo + (hi - lo) / 2;
      if (a[mid] == x)
        return binHigherBound(a, mid+1, hi, x);
      else if (a[mid] > x)
        return binHigherBound(a, lo, mid-1, x);
      else
        return binHigherBound(a, mid+1, hi, x);
    

Check if a given array contains duplicate elements within k distance , first_page Given a binary string, count number of substrings that start and end with 1. Next. last_page Find the missing number in Arithmetic Progression. Writing� Finding the count of duplicate numbers in a sorted array using binary search. Binary Search looks for a value in a sorted array. It compares the middle element of the array with the searched value. If the middle element equals the searched value, the position of the middle element is returned. If the middle element is bigger, the left portion of the array is searched using the same logic (binary search), else the right portion of the array is searched using binary search.

For the sake of completeness here's an example in typescript, non-recursive version (binary operators are used to enforce operations on integers rather than floating-point arithmetic) Example is easily convertible to other C-like languages:

function binarySearch(array: number[], query: number): [number, number] {
    let from: number;
    let till: number;

    let mid = 0 | 0;
    let min = 0 | 0;
    let max = array.length - 1 | 0;

    while (min < max) {
        mid = (min + max) >>> 1;

        if (array[mid] < query) {
            min = mid + 1 | 0;
        } else {
            max = mid - 1 | 0;
        }
    }

    mid = min;
    min--;
    max++;

    from = array[mid] < query ? (array[max] === query ? max : mid) : (array[mid] === query ? mid : min);

    min = 0 | 0;
    max = array.length - 1 | 0;

    while (min < max) {
        mid = (min + max) >>> 1;

        if (query < array[mid]) {
            max = mid - 1 | 0;
        } else {
            min = mid + 1 | 0;
        }
    }

    mid = min;
    min--;
    max++;

    till = array[mid] > query ? (array[min] === query ? min : mid) : (array[mid] === query ? mid : max);

    return [from, till];
}

Here's how it can be used:

let array = [1, 3, 3, 3, 5, 5, 5, 5, 5, 5, 7];

console.log(binarySearch(array, 0)); // Gives [ -1,  0 ] <= No value found, note that resulting range covers area beyond array boundaries
console.log(binarySearch(array, 1)); // Gives [  0,  0 ] <= Singular range (only one value found)
console.log(binarySearch(array, 2)); // Gives [  0,  1 ] <= Queried value not found, however the range covers argument value
console.log(binarySearch(array, 3)); // Gives [  1,  3 ] <= Multiple values found
console.log(binarySearch(array, 4)); // Gives [  3,  4 ] <= Queried value not found, however the range covers argument value
console.log(binarySearch(array, 5)); // Gives [  4,  9 ] <= Multiple values found
console.log(binarySearch(array, 6)); // Gives [  9, 10 ] <= Queried value not found, however the range covers argument value
console.log(binarySearch(array, 7)); // Gives [ 10, 10 ] <= Singular range (only one value found)
console.log(binarySearch(array, 8)); // Gives [ 10, 11 ] <= No value found, note that resulting range covers area beyond array boundaries

Find the only repeating element in a sorted array of size n , A naive approach is to scan the whole array and check if an element occurs twice , then return. This approach takes O(n) time. An efficient method is to use Binary� In a Binary Search Tree (BST), all keys in left subtree of a key must be smaller and all keys in right subtree must be greater. So a Binary Search Tree by definition has distinct keys. How to allow duplicates where every insertion inserts one more key with a value and every deletion deletes one occurrence?

public class a{
    public static int binarySearch(int[] array, int value, int left, int right) {
          if (left > right)
                return -1;
          int middle = (left + right) / 2;
          if (array[middle] == value)
        {
            if(array[middle-1]<array[middle])
                return middle;
                 //return binarySearch(array, value, left, middle - 1);
                 else
                return binarySearch(array, value, left, middle - 1);
        }
          else if (array[middle] > value)
                return binarySearch(array, value, left, middle - 1);
          else
                return binarySearch(array, value, middle + 1, right);           
    }
public static int binarySearch1(int[] array, int value, int left, int right) {
          if (left > right)
                return -1;
          int middle = (left + right) / 2;
          if (array[middle] == value)
        {
            if(array[middle]<array[middle+1])
                return middle; 
                 else

                    return binarySearch1(array, value, middle + 1, right);           
        }
          else if (array[middle] > value)
                return binarySearch1(array, value, left, middle - 1);
          else
                return binarySearch1(array, value, middle + 1, right);           
    }

    public static void main(String[] args) {
        int[] data = new int[] {10,20,21,24,24,24,24,24,30,40,45};


        System.out.println(binarySearch(data, 24, 0, data.length - 1));     //First Index
        System.out.println(binarySearch1(data, 24, 0, data.length - 1));    //Last Index
    }
}

Find duplicates algorithm series- A SORTED array as an input., inside an array when array contains 'n' items gives us O(n) time complexity thus defeats the purpose of using Binary Search which is famous� Find the duplicate.Example - A = [1,2,3,4,5,6,7,8,8] n = 9 (8). Given a limited range array of size n having elements from 1 to n-1 contains a duplicate. Find the duplicate.Example - A = [1,2,3,4,5,6,7,8,8] n = 9 (8).

Binary Search With Duplicates, of binary search assume that the target array has no duplicates. But sometimes there are duplicates, and in that case you want to find the first� Check if a given array contains duplicate elements within k distance from each other; Find Itinerary from a given list of tickets; Find number of Employees Under every Employee; Check if an array can be divided into pairs whose sum is divisible by k; Find four elements a, b, c and d in an array such that a+b = c+d

Binary Search — Java Review, Binary search calculates the middle index as the left + right / 2 where left starts out at 0 and right starts out If the target value is greater than the value at the middle it sets left to middle plus one. The array must not contain duplicate values. Find a duplicate in an array Given an array of n + 1 integers between 1 and n, find one of the duplicates. If there are multiple possible answers, return one of the duplicates. If there is no

Find a Duplicate in an Array. Given an array of n + 1 integers…, It works if 'n' is not big. Given an array A of 'm' of nonnegative integers in the range [0..n], find duplicates. Allocate a histogram array of size� Given a sorted array of integers containing duplicates, count occurrences of a number provided. If the element is not found in the array, report that as well. We can easily solve this problem in O(log(n)) time by modifying binary search algorithm. The idea is to find the index of first and last occurrence of given num

Comments
  • Are you asking, 'if i were to implement a binary search and was given this array and asked to find the index of 24, what should I return?' or are you asking 'if I ran this array through someone else's implementation of a binary search, which I am too lazy to do, what would the return value be?'
  • You can tell those both scenarios if possible..that would be appreciated...
  • Obviously result will be array[5].
  • brilliant! tested only lower bound though!