Created
August 26, 2021 04:55
-
-
Save pavanesh2021/0cdf3a76fcd8f6807349c98275ec1719 to your computer and use it in GitHub Desktop.
JS Bin // source https://jsbin.com/vakuqik
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<script id="jsbin-javascript"> | |
function binarySearch(value, arr) { | |
let left = 0; | |
let right = arr.length - 1; | |
while (left <= right) | |
{ | |
const mid = left + Math.floor((right - left) / 2); | |
if (value === arr[mid]) | |
{ | |
return mid; | |
} | |
// case 1: when value is lower than middle then search only on LEFT side. | |
if (value < arr[mid]) | |
{ | |
right = mid - 1; | |
} else | |
{ | |
left = mid + 1; | |
} | |
//case 2: when value is higher than middle then search only on RIGHT side. | |
} | |
return -1; | |
} | |
const valuesGiven = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
console.log(binarySearch(5, valuesGiven)); | |
</script> | |
<script id="jsbin-source-javascript" type="text/javascript">function binarySearch(value, arr) { | |
let left = 0; | |
let right = arr.length - 1; | |
while (left <= right) | |
{ | |
const mid = left + Math.floor((right - left) / 2); | |
if (value === arr[mid]) | |
{ | |
return mid; | |
} | |
// case 1: when value is lower than middle then search only on LEFT side. | |
if (value < arr[mid]) | |
{ | |
right = mid - 1; | |
} else | |
{ | |
left = mid + 1; | |
} | |
//case 2: when value is higher than middle then search only on RIGHT side. | |
} | |
return -1; | |
} | |
const valuesGiven = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
console.log(binarySearch(5, valuesGiven));</script></body> | |
</html> |
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
function binarySearch(value, arr) { | |
let left = 0; | |
let right = arr.length - 1; | |
while (left <= right) | |
{ | |
const mid = left + Math.floor((right - left) / 2); | |
if (value === arr[mid]) | |
{ | |
return mid; | |
} | |
// case 1: when value is lower than middle then search only on LEFT side. | |
if (value < arr[mid]) | |
{ | |
right = mid - 1; | |
} else | |
{ | |
left = mid + 1; | |
} | |
//case 2: when value is higher than middle then search only on RIGHT side. | |
} | |
return -1; | |
} | |
const valuesGiven = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
console.log(binarySearch(5, valuesGiven)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment