Skip to content

Commit cefcb86

Browse files
author
Prashant Jain
committed
Added binary search
1 parent 391992d commit cefcb86

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package in.knowledgegate.dsa.binarysearch.algos;
2+
3+
/**
4+
* implement Binary Search on sorted array
5+
* Example:
6+
* sortedArr: -8, -5, 0, 3, 7, 11, 15
7+
* Number to find: 7
8+
* Number to find: 1
9+
*/
10+
public class BinarySearch {
11+
public int search(int[] sortedArr, int target) {
12+
int beg = 0, end = sortedArr.length - 1;
13+
while (beg <= end) {
14+
int mid = beg + (end - beg) / 2;
15+
if (target == sortedArr[mid]) {
16+
return mid;
17+
} else if (target < sortedArr[mid]) {
18+
end = mid - 1;
19+
} else {
20+
beg = mid + 1;
21+
}
22+
}
23+
return -1;
24+
}
25+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package in.knowledgegate.dsa.binarysearch.problems;
2+
3+
/**
4+
* Given a non-negative integer x, compute and
5+
* return the square root of x.
6+
*
7+
* Since the return type is an integer, the
8+
* decimal digits are truncated, and only the
9+
* integer part of the result is returned.
10+
*
11+
* Note: You are not allowed to use any built-in
12+
* exponent function or operator, such as
13+
* pow(x, 0.5) or x ** 0.5.
14+
*
15+
* Example 1:
16+
* Input: x = 4
17+
* Output: 2
18+
*
19+
* Example 2:
20+
* Input: x = 8
21+
* Output: 2
22+
* Explanation: The square root of 8 is 2.82842...,
23+
* and since the decimal part is truncated,
24+
* 2 is returned.
25+
*
26+
*
27+
* Constraints:
28+
* 0 <= x <= 231 - 1
29+
*/
30+
public class SquareRoot {
31+
public int mySqrt(int x) {
32+
int beg = 0, end = x;
33+
while (beg <= end) {
34+
int mid = beg + (end - beg) / 2;
35+
long square = ((long)mid) * mid;
36+
if (square == x) {
37+
return mid;
38+
} else if (square > x) {
39+
end = mid - 1;
40+
} else {
41+
beg = mid + 1;
42+
}
43+
}
44+
return end;
45+
}
46+
}

0 commit comments

Comments
 (0)