Life Hacks


      

Write a program of the Binary Search.



#include<iostream.h>

#include<conio.h>

void main( ) /* main start */

{

clrscr( );

int a[20], n, c, lb, ub, item, mid, loc; /* local variable */

cout << " \n Enter the number of elements in an array is: " << " \n ";

cin>>n; // entering no. of elements for the array.

cout << " \n Enter the value of elements of array is: " << " \n ";

for(c = 1; c <= n; c++) // entering values of elements of array.

{

cin >> a[c];

} /* End of for loop*/

cout << " \n Enter the number to be searched: ";

cin >> item; // enter the number for searching.

lb = 1; // set Lower Bound.

ub = n; // set Upper Bound.

mid = (lb + ub) / 2;

while((lb <= ub) && (a[mid] != item))

{

if(item > a[mid])

{

lb = mid + 1;

}

else

{

ub = mid – 1;

}

mid = (lb + ub) / 2;

} /* End of while loop*/

if(item = = a[mid])

{

// executes this code if the element is available in the list.

loc = mid;

cout << " \n The" << " " << item << " is at position: " << loc;

}

else

{

// executes this code if the element is not available in the list.

cout << " \n The " << " " << item << " is not in the list ";

}

getch( );

}

Output:-

clip_image002

Leave a Reply