Created
October 21, 2022 13:12
-
-
Save BillRizer/22cd032d79d0549680b17a6a76ff7be6 to your computer and use it in GitHub Desktop.
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
export const search=(arr:Array<number>,target:number) =>{ | |
let loops =1 | |
let indexStart = 0; | |
let indexEnd = arr.length - 1; | |
while(indexStart <= indexEnd){ | |
const indexMid = Math.floor((indexStart + indexEnd) / 2); | |
if(arr[indexMid] === target){ | |
console.log('loop N ->',loops) | |
return indexMid | |
} | |
if(arr[indexMid] > target){ | |
indexEnd = indexMid -1 | |
} | |
if(arr[indexMid] < target){ | |
indexStart = indexMid +1 | |
} | |
loops++ | |
} | |
return -1 | |
} | |
const array = [...Array(1000).keys()].map(a=>a+45) | |
console.log('binary search:'); | |
const target = 9 | |
const indexFound = search(array,target) | |
console.log("index", indexFound, " ",array[indexFound], "== ",target) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment