You are on page 1of 4

/* This program inputs an ORDERED list of integers and given a search key*/

/* searches for it in the list*/

#include <iostream.h>

#include <stdlib.h>

#include<conio.h>

#include <math.h>

#define SIZE 25

int n=0;

int binary_search(int [], int, int,int *);

int main(void)

int i, option, flag,key,*locn;

int L[SIZE];

clrscr();

while (1)

{ /* main menu*/

cout<<" 1. Input ordered list\n";

cout<<" 2. Search for key using Binary search\n";

cout<<" 3. Quit\n";

cout<<"\n Enter option";

cin>>option;

switch(option)

case 1: cout<<"Number of elements?\n"; /*input ordered list*/

cin>>n;

cout<<"Input ordered list of elements\n";


for (i=0; i<n; i++)

L[i]=0;

cin>>L[i];

break;

case 2: cout<<"Enter search key!\n"; /* input search key and initiate


search*/

cin>>key;

flag=binary_search(L, key,n-1,locn); /*L[1:n] is the list where key is


to be searched*/

if(flag==1)

cout<<"\nData is found\n";

cout<<"Location is: "<<*locn+1;

else

cout<<"\nData is not found\n";

break;

case 3:

for (i=0; i<n; i++)

L[i]=0;

exit(0);

break;

default: cout<<"Illegal option\n";

getch();
}

int binary_search(int l[], int target, int end, int *locn1)

/* l[first:last] is a linear ordered sublist of data elements*/

/* target is the key to be searched in the list */

int mid,first,last;

first=0;

last=end;

while (first<=last)

mid = ceil((first+last)/2);

if(target > l[mid])

first = mid+1; /* search for key K in L[low:mid-1]*/

else

if(target < l[mid])

last = mid-1; /* search for key K in L[mid+1: high]*/

else

break;

*locn1 = mid;

/*if (tar ==l[mid])

flag = 1;

else

flag=0;
return flag;*/

return (target==l[mid]);

You might also like