From 56d220bcc5be6ef5a6bda75ca4bd3828f2d28924 Mon Sep 17 00:00:00 2001 From: Akash Negi <55234838+NegiAkash890@users.noreply.github.com> Date: Fri, 29 Jan 2021 20:25:22 +0530 Subject: [PATCH] ADD - binary-search-recursive (#46) * ADD - binary-search-recursive This file contains recursive version of the Binary Search . * Updated README.md --- searching/README.md | 3 +- searching/js/binary-search-recursive.js | 52 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 searching/js/binary-search-recursive.js diff --git a/searching/README.md b/searching/README.md index 269013d0..54eba9bb 100644 --- a/searching/README.md +++ b/searching/README.md @@ -15,7 +15,8 @@ ### JavaScript 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 diff --git a/searching/js/binary-search-recursive.js b/searching/js/binary-search-recursive.js new file mode 100644 index 00000000..1c5bba30 --- /dev/null +++ b/searching/js/binary-search-recursive.js @@ -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