forked from iam-abbas/cs-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBinary Search.cpp
More file actions
53 lines (43 loc) · 825 Bytes
/
Binary Search.cpp
File metadata and controls
53 lines (43 loc) · 825 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
// Coding Binary Search Algorithm through Functions Topic Approach
#include<iostream>
using namespace std ;
int BinarySearch(int arr[] ,int n , int val )
{
int start=0 ;
int end=n-1 ;
int mid ;
while(start<=end)
{
mid=(start+end)/2 ;
if(val==arr[mid])
{
return mid ;
}
else if(val > arr[mid])
{
start=mid+1 ;
}
else
{
end=mid-1 ;
}
}
return -1 ;
}
int main()
{
int arr[50],n ;
int result ;
cout << "Enter the no. of elements do u want to enter" ;
cin >> n ;
cout << "Enter the elements that you want to insert in the Array " << endl ;
for(int i=0 ; i<n ; i++)
{
cin >> arr[i] ;
}
cout << "Enter the element that you want to search for in the Array" << endl ;
int val ;
cin >> val ;
result= BinarySearch(arr,n,val) ;
cout << result << endl ;
}