Last active
November 25, 2020 22:50
-
-
Save mksglu/31ca2f1f18cee9031fce79e2870fc9b7 to your computer and use it in GitHub Desktop.
Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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)); |
Author
mksglu
commented
Nov 23, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment