Answer to Question #223804 in HTML/JavaScript Web Application for Laraib

Question #223804
Create an array of 20 entries.
search these entries by different algorithms.
1
Expert's answer
2021-08-06T15:32:11-0400
//  Binary search
<script>
let recursiveFunction = function (arr, x, start, end) {
       
    // Base Condition
    if (start > end) return false;
   
    // Find the middle index
    let mid=Math.floor((start + end)/2);
   
    // Compare mid with given key x
    if (arr[mid]===x) return true;
          
    // If element at mid is greater than x,
    // search in the left half of mid
    if(arr[mid] > x) 
        return recursiveFunction(arr, x, start, mid-1);
    else
  
        // If element at mid is smaller than x,
        // search in the right half of mid
        return recursiveFunction(arr, x, mid+1, end);
}
   
// Driver code
let arr = [0, 0, 1, 1, 2, 3, 3, 3, 4, 5, 7, 7, 8, 8, 8, 9, 11, 12, 14, 32];
let x = 5;
   
if (recursiveFunction(arr, x, 0, arr.length-1))
    document.write("Element found!<br>");
else document.write("Element not found!<br>");
   
x = 6;
   
if (recursiveFunction(arr, x, 0, arr.length-1))
    document.write("Element found!<br>");
else document.write("Element not found!<br>");
</script>

Output:
Element found!
Element not found!

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS