Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

search insert elements using binary search method in one dimensional array

 function binarySearch(a,x,low,high)

    {

      

           const mid=(low+high)/2;

            if(x==a[mid])

            {

                console.log("element is present at position"+mid);

            }

            else if(x>a[mid])

            {

                low=mid+1;

                for(let i=low;i<=high;i++)

                    {

                        if(a[i]==x)

                        {

                            console.log(x,"elemet is presnet at",i);

                        }

                       

                    }

            }

            else

            {

            for(let i=low;i<mid;i++)

                {

                    if(a[i]==x)

                    {

                        console.log(x,"elemnet is present at position",i);

                    }

                }

           

            }

       

           

       

    }

 

 

let  a=[90,20,30,40,50,60,70,80,10];

let  x=70;

let low=0;

console.log("Before Sort",a);

let b=a.sort(function compare(a,b){return a-b});

console.log("After Sort:",b);

let high=a.length-1;

binarySearch(a,x,low,high);

 

 

 

 

 

Output :

 

Before Sort (9) [90, 20, 30, 40, 50, 60, 70, 80, 10]

 After Sort: (9) [10, 20, 30, 40, 50, 60, 70, 80, 90]

 70 'element is present at'  6

Post a Comment

0 Comments

Ad Code

Responsive Advertisement