-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment1.2.cpp
More file actions
55 lines (46 loc) · 972 Bytes
/
Copy pathAssignment1.2.cpp
File metadata and controls
55 lines (46 loc) · 972 Bytes
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
// binary search for sorted array
// Annie Bhalla
// 19HCS4009
#include<iostream>
using namespace std;
int binarySearch(int size, int array[], int value)
{
int start=0;
int end=size-1;
int middle;
while(start<=end )
{
middle = (start+end)/2;
if(array[middle]==value)
{
return middle+1;
}
else if(value<array[middle])
end=middle-1;
else if(value>array[middle])
start = middle +1;
}
return -1;
}
int main()
{
int *array;
int N;
int value;
cout<<"\n Enter the size of the array : ";
cin>>N;
array = new int[N];
cout<<"\n Enter the elements in the array "<<endl;
for(int i=0;i<N;i++)
{
cin>>array[i];
}
cout<<"\n Enter the value you wish to search in the array :";
cin>>value;
int index=binarySearch(N,array,value);
if(index==-1)
cout<<"\n Element not found ";
else
cout<<"\n Element "<<value<<" found at position "<<index;
return 0;
}