Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update BinarySearch.js
Style change
  • Loading branch information
Askanders authored Jun 27, 2020
commit ee9a03d48a85f7c7f66bec148569468d7510a2da
76 changes: 38 additions & 38 deletions Search/BinarySearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,64 +7,64 @@
* value is found or the interval is empty.
*/

function binarySearch(arr, x, low = 0, high = arr.length - 1) {
let mid = Math.floor(low + (high - low) / 2);
function binarySearch( arr, x, low = 0, high = arr.length - 1 ) {
const mid = Math.floor(low + (high - low) / 2)

if (high >= low) {
if (arr[mid] === x) {
// item found => return its index
return mid;
return mid
}

if (x < arr[mid]) {
// arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
return binarySearch(arr, x, low, mid - 1);
return binarySearch(arr, x, low, mid - 1)
} else {
// arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
return binarySearch(arr, x, mid + 1, high);
return binarySearch(arr, x, mid + 1, high)
}
} else {
// if low > high => we have searched the whole array without finding the item
return -1;
return -1
}
}

/* ---------------------------------- Test ---------------------------------- */

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stringArr = [
"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
"Golf",
"Hotel",
"India",
"Juliet",
"Kilo",
"Lima",
"Mike",
"November",
"Oscar",
"Papa",
"Quebec",
"Romeo",
"Sierra",
"Tango",
"Uniform",
"Victor",
"Whiskey",
"X-Ray",
"Yankee",
"Zulu",
'Alpha',
'Bravo',
'Charlie',
'Delta',
'Echo',
'Foxtrot',
'Golf',
'Hotel',
'India',
'Juliet',
'Kilo',
'Lima',
'Mike',
'November',
'Oscar',
'Papa',
'Quebec',
'Romeo',
'Sierra',
'Tango',
'Uniform',
'Victor',
'Whiskey',
'X-Ray',
'Yankee',
'Zulu',
];

console.log(binarySearch(arr, 3));
console.log(binarySearch(arr, 7));
console.log(binarySearch(arr, 13));
console.log(binarySearch(arr, 3))
console.log(binarySearch(arr, 7))
console.log(binarySearch(arr, 13))

console.log(binarySearch(stringArr, "Charlie"));
console.log(binarySearch(stringArr, "Zulu"));
console.log(binarySearch(stringArr, "Sierra"));
console.log(binarySearch(stringArr, "Charlie"))
console.log(binarySearch(stringArr, "Zulu"))
console.log(binarySearch(stringArr, "Sierra"))