Skip to content

Instantly share code, notes, and snippets.

@mksglu
Last active November 25, 2020 22:50
Show Gist options
  • Save mksglu/31ca2f1f18cee9031fce79e2870fc9b7 to your computer and use it in GitHub Desktop.
Save mksglu/31ca2f1f18cee9031fce79e2870fc9b7 to your computer and use it in GitHub Desktop.
Binary Search
/*
1. Initialize left=1 & Right=n
2. Calculate mid = Math.floor((left + right) / 2);
2. If mid*mid = n, then n is Perfect Square
3. Else if mid*mid > n then right = mid - 1
4. Else if mid*mid < n then left = mid + 1
*/
const perfectSquare = (number) => {
let left = 1;
let right = number;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
let square = mid * mid;
if (square === number) {
return true;
} else if (square < number) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
};
console.log(perfectSquare(1));
@mksglu
Copy link
Author

mksglu commented Nov 23, 2020

image

@mksglu
Copy link
Author

mksglu commented Nov 23, 2020

Binary Search vs Sequential Search:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment