Added binary-search.js (#43)
* Add - binary-search-iterative * Deleted binary-search-iterative.js * Updated binary-search.jspull/50/head
parent
da54204438
commit
1724bf6b03
|
@ -1,24 +1,34 @@
|
||||||
function binarySearch(value, list) {
|
|
||||||
let first = 0; //left endpoint
|
|
||||||
let last = list.length - 1; //right endpoint
|
|
||||||
let position = -1; // After looping if the search item is not found, we will return -1
|
|
||||||
let found = false; // When item is found we set its value to true
|
|
||||||
let middle;
|
|
||||||
|
|
||||||
while (found === false && first <= last) {
|
|
||||||
middle = Math.floor((first + last)/2);
|
/* In this We will learn how to search for an item in Sorted array using Binary Search .*/
|
||||||
if (list[middle] == value) { // If the element is present at the middle itself
|
|
||||||
found = true;
|
function binarySearch( item , arr ) {
|
||||||
position = middle;
|
let first = 0; //left endpoint or index of first array element
|
||||||
} else if (list[middle] > value) { //if in lower half
|
let last = arr.length - 1; //right endpoint or index of lat array element .
|
||||||
|
|
||||||
|
while (first <= last) {
|
||||||
|
let middle = Math.floor((first + last)/2);
|
||||||
|
if ( arr[middle] == item ) {
|
||||||
|
// If the element is present at the middle itself
|
||||||
|
return middle ;
|
||||||
|
|
||||||
|
}
|
||||||
|
else if ( arr[middle] > item ) {
|
||||||
|
// Ignore Right Half i.e. items after middle element .
|
||||||
last = middle - 1;
|
last = middle - 1;
|
||||||
} else { //in in upper half
|
}
|
||||||
|
else {
|
||||||
|
// Ignore Right Half i.e. items after middle element .
|
||||||
first = middle + 1;
|
first = middle + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return position;
|
return -1; //Item is not present in Array .
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(binarySearch(6,[2, 6, 8])); //expected output = 1
|
console.log(binarySearch(6,[2, 6, 8])); //expected output = 1
|
||||||
console.log(binarySearch(10,[2, 3, 10, 14])); //expected output = 2
|
console.log(binarySearch(10,[2, 3, 10, 14])); //expected output = 2
|
||||||
console.log(binarySearch(1,[2, 6, 8])); //expected output = -1
|
console.log(binarySearch(1,[2, 6, 8])); //expected output = -1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue