ADD - binary-search-recursive (#46)

* ADD - binary-search-recursive

This file contains recursive version of the Binary Search .

* Updated README.md
pull/50/head
Akash Negi 2021-01-29 20:25:22 +05:30 committed by GitHub
parent 1724bf6b03
commit 56d220bcc5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 1 deletions

View File

@ -15,7 +15,8 @@
### JavaScript ### JavaScript
1. [Linear Search](js/linear-search.js) 1. [Linear Search](js/linear-search.js)
2. [Binary Search](js/binary-search.js) 2. [Binary Search ( Iterative )](js/binary-search.js)
3. [Binary Search ( Recursive )](js/binary-search-recursive.js)
### Java ### Java

View File

@ -0,0 +1,52 @@
//Recursive Method
/*Arguments to Function
arr - array ( Sorted Only )
low - lower index of array (0)
high - max index of array (length of array - 1 )
item = Element to be searched .
*/
function binary_recurrence(arr, low, high, item) {
// Base Case for the termination of Recursion
if(low > high) {
return -1 ; //Item is not present in the Array
}
// Calculating Mid Index
let mid = Math.floor((low+high)/2) ;
//Equation Middle Element with the item to be searched
if(arr[mid] == item ){
// Middle Element equal to the Item
// We found Element at the mid Index
return mid ;
}
else if( arr[mid] > item ){
// Item is less than the middle Element
// Ignore the Right Half , as right half contains elements greater than middle element and so item too .
// Make a recursive call to the left Half
return binary_recurrence(arr,low,mid-1,item);
}
else {
//Item is greater than the middle Element
//Ignore the Left Half ,as left half contains element less than middle element and so item too .
//Make recursive call to the right Half
return binary_recurrence(arr,mid+1,high,item);
}
}
console.log(binary_recurrence([1,3,5,7,8,9], 0, 5, 7)); //returns 3 , Found at Index 3
console.log(binary_recurrence([1,3,5,7,8,9], 0, 5, 10)); //returns -1 , 10 is not present in array