We suggest you do not use library functions for binary search as its very likely that you will be explicitly asked to implement the binary search in interviews.
// binary search example in C/C++
/* here Arr is an of integer type, n is size of array
and target is element to be found */
int binarySearch(int *Arr, int n, int target) {
//set stating and ending index
int start = 0, ending = n-1;
while(start <= ending) {
// take mid of the list
int mid = (start + end) / 2;
// we found a match
if(Arr[mid] == target) {
return mid;
}
// go on right side
else if(Arr[mid] < target) {
start = mid + 1;
}
// go on left side
else {
end = mid - 1;
}
}
// element is not present in list
return -1;
}
// binary search example in Java
/* here Arr is an of integer type, n is size of array
and target is element to be found */
int binarySearch(int Arr[], int n, int target) {
//set stating and ending index
int start = 0, ending = n-1;
while(start <= ending) {
// take mid of the list
int mid = (start + end) / 2;
// we found a match
if(Arr[mid] == target) {
return mid;
}
// go on right side
else if(Arr[mid] < target) {
start = mid + 1;
}
// go on left side
else {
end = mid - 1;
}
}
// element is not present in list
return -1;
}
# binary search example in Python
# here Arr is an of integer type, n is size of array
# and target is element to be found
def binarySearch(Arr, n, target) :
#set stating and ending index
start, end = 0, n-1
while start <= end :
mid = (start + end) / 2
# we found a match
if Arr[mid] == target :
return mid
# go on right side
elif Arr[mid] < target :
start = mid + 1
# go on left side
else :
end = mid - 1;
# element is not present in list
return -1
Walkthrough Examples :
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Search in Bitonic Array! | 100 |
|
53:22 | |
Smaller or equal elements | 200 |
|
33:04 | |
WoodCutting Made Easy! | 200 |
|
59:06 | |
Matrix Search | 250 |
|
36:51 | |
Search for a Range | 250 |
|
42:02 | |
Sorted Insert Position | 250 |
|
25:03 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Capacity To Ship Packages Within B Days | 200 |
|
48:21 | |
Matrix Median | 225 |
|
77:24 | |
Square Root of Integer | 275 |
|
40:32 | |
Allocate Books | 350 |
|
68:01 | |
Painter's Partition Problem | 350 |
|
81:38 | |
Red Zone | 400 |
|
45:14 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Implement Power Function | 275 |
|
59:44 | |
Simple Queries | 300 |
|
67:38 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Median of Array | 325 |
|
87:06 | |
Rotated Sorted Array Search | 325 |
|
56:53 |