Binary Search Using Recursion JavaScript Example


Share:
Published By: Admin, Published On: Oct 19, 2021, Category: Javascript


Hello Friends,

Now let's see example of how to use binary search using recursion example. We will use how to binary search using recursion in javascript. Here you will learn how to use javascript binary search using recursion. This is a short guide on binary search using recursion. Let's get started with how to find binary search using recursion in javascript.

Here i will give you many example how you can binary search using recursion javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Binary Search Using Recursion JavaScript Example - MyWebtuts.com</title>
    </head>
    <body>
        <h2>Binary Search Using Recursion JavaScript Example - MyWebtuts.com</h2>
        <h4>Output : 5</h4>
        <script type="text/javascript">
            Array.prototype.binSearch = function (binary) 
            {
                var half = parseInt(this.length / 2);
                if (binary === this[half]) 
                {
                    return half;
                }
                if (binary > this[half]) 
                {
                    return half + this.slice(half,this.length).binSearch(binary);
                } 
                else
                {
                    return this.slice(0, half).binSearch(binary);
                }
            };
            demo = [0,1,2,3,4,5,6];

            console.log(demo.binSearch(5));
        </script>
    </body>
</html>
Output :
5
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Binary Search Using Recursion JavaScript Example - MyWebtuts.com</title>
    </head>
    <body>
        <h2>Binary Search Using Recursion JavaScript Example - MyWebtuts.com</h2>
        <h4>Output :  1, null</h4>
        <script type="text/javascript">
            const binSearch = ( list, item ) => {
                let low = 0;
                let high = list.length - 1;

                while ( low <= high ) {
                    let mid = Math.floor((low + high) / 2);
                    let guess = list[mid];

                    if ( guess === item ) {
                        return mid;
                    } else if ( guess > item ) {
                        high = mid - 1;
                    } else {
                        low = mid + 1;
                    }
                }
                return null;
            };
            const listBin = [1, 3, 4, 9, 5];

            console.log( binSearch( listBin, 3 ) );
            console.log( binSearch( listBin, -1 ) );
        </script>
    </body>
</html>
Output :
1, null

It will help you...

Share: