Last active
January 31, 2018 19:25
-
-
Save ti-ka/24c5fb6720d953150efd71dad437e2fa to your computer and use it in GitHub Desktop.
Binary search on a sorted array using recursion: https://jsbin.com/pilitor/edit?js,console
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
// Task: | |
// Find an item in an sorted array. | |
var array = [1,3,4,6,7,8,8,9,10,56,102,200,230] | |
var item = 200 | |
var globalCounter = 0 | |
console.log(binarySearch(array, item)) | |
console.log("iterated " + globalCounter + " time/s.") | |
function binarySearch(array, item, leftIndex, rightIndex) { | |
// Count "O" | |
globalCounter++ | |
if (leftIndex === undefined) leftIndex = 0; | |
if (rightIndex === undefined) rightIndex = array.length - 1; | |
var midIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2); | |
if (leftIndex > rightIndex) { | |
return false; | |
} | |
if (array[midIndex] === item) { | |
return true; | |
} else if (item < array[midIndex]) { | |
return binarySearch(array, item, leftIndex, midIndex - 1); | |
} else { | |
return binarySearch(array, item, midIndex + 1, rightIndex); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment