Most implementations 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 occurrence of an item, not just any one of several occurrences. For instance, in the array [1,2,2,3,4,4,4,4,6,6,6,6,6,6,7] the first occurrence of 4 is at element 4 (counting from 0), the first occurrence of 6 is at element 8, and 5 does not appear in the array.

Your task is to write a binary search that finds the first occurrance of a set of duplicate items in a sorted array. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.


Pages: 1 2