![]() |
VOOZH | about |
Given a sorted array consisting 0's and 1's. The problem is to find the index of first '1' in the sorted array. It could be possible that the array consists of only 0's or only 1's. If 1's are not present in the array then print "-1".
Examples :
Input : arr[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1}
Output : 6
Explanation: The index of first 1 in the array is 6.Input : arr[] = {0, 0, 0, 0}
Output : -1
Explanation: 1's are not present in the array.
Table of Content
Traverse the array from left to right and return the index of first '1'. If 1's are not present in the array, then print "-1"
6
Use the technique of binary search on the sorted array, so as to find the index of first '1'.
Algorithm:
low = 0 and high = n - 1. mid = (low + high) / 2 and check the value at mid. arr[mid] == 1 and it is the first occurrence, return mid. arr[mid] == 1, move left (high = mid - 1); else move right (low = mid + 1). -1.6