Computer Science, asked by rohitqumar123, 11 months ago

write a program in c++ to read an array of sorted integers search for value using binary search method if the element is found print its location else print element not found

Answers

Answered by sailorking
47

#include<iostream.h>

#include<conio.h>

void main()

{

    clrscr();

    int arr[30],first,number,last,count;

    first=0;

    cout<<"Enter the number of inputs "<<endl;

     cin>>count;

      for(int i=0;i<count;i++)

       {

          cout<<"Enter the number"<<endl;

          cin>>arr[i];

        }

       cout<<"Enter the number to be searched"<<endl;

       cin>>number;

       last=count-1;

        middle=(first+last)/2;

       while(first<=last)

       {

         if(arr[middle] < number)

   {

 first = middle + 1;


   }

   else if(arr[middle] == number)

   {

 cout<<number<<" found in the array at the location "<<middle+1<<"\n";

               break;

          }

          else {

               last = middle - 1;

          }

          middle = (first + last)/2;

       }

       if(first > last)

{

   cout<<number<<" not found in the array";

}

return 0;

}

        }

}

Similar questions