-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
65 lines (49 loc) · 1 KB
/
BinarySearch.cpp
File metadata and controls
65 lines (49 loc) · 1 KB
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
/*
WAP for Binary search of an element in an array
*/
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int binarysearch(int [], int, int);
void isValid(int);
int size, arr[100], ele, pos;
cout<<"Enter size of array<100 : ";
cin>>size;
isValid(size); //to check if entered sizs is in given range or not
for(int i=0;i<size;i++) //enter array elements
cin>>arr[i];
cout<<endl<<"Enter element to be searched : ";
cin>>ele;
pos=binarysearch(arr,size,ele); //function call
if(pos!=-1)
cout<<endl<<"Element is found at position : "<<pos+1<<endl;
else
cout<<endl<<"Not found!!!"<<endl;
return 0;
}
void isValid(int z)
{
if(z<=0||z>100)
{
cout<<endl<<"Enter in the given range!!!";
}
else
cout<<endl<<"Enter array elements in ascending order only:\n";
}
int binarysearch(int arr[], int size, int ele)
{
int beg=0, last=size-1, mid;
while(beg<=last)
{
mid=((beg+last)/2);
if(ele==arr[mid])
return mid;
else if(ele<mid)
last=mid-1;
else
beg=mid+1;
}
return -1;
}