searching algorithms in javascript
function searchAlgorithm (number){
for(let i = 0; i< number; i++){
if(number == array[i]){
console.log("Found it, it's at index " + i)
}else{
console.log("Not found")
}
};
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
searchAlgorithm(5)
4.5
2
// Binary Search is the most efficient algorithm.
function binarySearch(value, list) {
let first = 0; //left endpoint
let last = list.length - 1; //right endpoint
let position = -1;
let found = false;
let middle;
while (found === false && first <= last) {
middle = Math.floor((first + last)/2);
if (list[middle] == value) {
found = true;
position = middle;
} else if (list[middle] > value) { //if in lower half
last = middle - 1;
} else { //in in upper half
first = middle + 1;
}
}
return position;
}
Thank you!
2
0
Are there any code examples left?
New code examples in category Javascript