WELCOME TO MY BLOG BY SHABEEB.K

C,C++ PROGRAMMING: BINARY SEARCH

Search This Blog

Wednesday, 27 November 2013

BINARY SEARCH


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<iostream.h>
#include<conio.h>

int low=0;
int flag=0;
int j=0;

class searching
{
public:

int a[50];
int mid,high;
int i;
int size;
int el;

void read()
{
cout<<"ENTER ARRAY SIZE\n";  //input array size to enter elements if u enter array size 5 then u can insert 5 elements into array. 
cin>>size;

cout<<"ENTER ELEMENTS\n";  

for(i=0;i<size;i++)
{
cin>>a[i];                  //enter elements to array untile array size full.
}
}

void input()          ti  //a funcon to enter input to search for an element from already entred array.
{
cout<<"ENTER ELEMENTS to search\n";
cin>>el;                  
high=size;          //initilized high is equals to size.
}

void search()
{
j++;

mid=(high+low)/2;  //calculating midle value of sorted array

if(el==a[mid])      //to check if search for an element found at any location in array. 
{
cout<<"ELEMENT "<<el<<" FOUND AT LOCATION "<<mid<<"\n";  //if element is found this message is displayed to the user.

flag=1;                                                  //element is found so we set flag=1 for a reference.
}

                      

if(el<a[mid])                                         //if search for element< middle value  we set high=mid
{
high=mid;       
}
else                                             
{
low=mid;                                               //if search for element>midle value is we set low=mid
}

if(j<=size && el!=a[mid])              //continue the search fundtion untile element is found.
{
search();
}

if(flag==0)
{
cout<<"ELEMENT WAS NOT FOUND\n";          //if flag=0 which means search for element not found at any lcation.
}
}
};

void main()
{
clrscr();
searching s;

s.read();  //calling read function.
s.input(); //calling input function.
s.search(); //search function.
getch();
}

No comments:

Post a Comment