MCPcopy Create free account
hub / github.com/Manvityagi/PW-Skills-Java-Course-Codes / Main

Class Main

Lecture 45 - Binary Search/src/Main.java:1–71  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1public class Main {
2 static int findSquareRoot(int x) {
3 int st = 0, end = x, ans = -1;
4 while (st <= end) {
5 int mid = st + (end - st) / 2;
6 int val = mid * mid; // you can use long to avoid overflow error
7 if (val == x)
8 return mid;
9 else if (val < x) {
10 ans = mid;
11 st = mid + 1;
12 } else
13 end = mid - 1;
14 }
15 return ans;
16 }
17 static int firstOcc(int[] a, int val){
18 int st = 0, end = a.length-1;
19 int fo = -1;
20 while(st <= end){
21 int mid = st + (end-st)/2;
22 if(val == a[mid]){
23 fo = mid;
24 end = mid-1;
25 } else if(val < a[mid]){
26 end = mid-1;
27 } else {
28 st = mid+1;
29 }
30 }
31 return fo;
32 }
33 static boolean recBinarySearch(int[] a, int st, int end, int val) {
34 if (st > end) return false;
35 int mid = (st + end) / 2; // find middle element of the array
36 if (a[mid] == val)
37 return true; // value found
38 else if (val < a[mid])
39 return recBinarySearch(a, st, mid - 1, val);
40 else
41 return recBinarySearch(a, mid + 1, end, val);
42 }
43
44 static boolean binarySearch(int[] a, int val) {
45 int n = a.length;
46 int st = 0, end = n - 1; // 0 based indexing
47 while (st <= end) {
48 int mid = (st + end) / 2; // find middle element of the array
49 if (a[mid] == val)
50 return true; // value found
51 else if (val < a[mid])
52 end = mid - 1;
53 else
54 st = mid + 1;
55 }
56 return false; // value not found in the array
57 }
58
59 public static void main(String[] args) {
60 int[] a = {1, 2, 3, 4, 5};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected