-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
35 lines (35 loc) · 850 Bytes
/
Copy pathBinarySearch.cpp
File metadata and controls
35 lines (35 loc) · 850 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
#include<iostream>
using namespace std;
int search(int arr[], int x, int elfirst, int ellast)
{
while(elfirst<=ellast)
{
int mid=elfirst+(ellast-elfirst)/2;
if(arr[mid]==x)
return mid;
if(arr[mid]<x)
elfirst=mid+1;
else
ellast=mid-1;
}
return -1;
}
int main()
{
int a[25], n, toFind;
cout<<"\nEnter the number of elements you want in the array: ";
cin>>n;
cout<<"\nEnter the elements: ";
for(int i=0; i<n; i++)
{
cin>>a[i];
}
cout<<"\nEnter the number you want to search: ";
cin>>toFind;
int result=search(a, toFind, 0, n-1);
if(result==-1)
cout<<"\nThe element "<<toFind<<" was not found in the array";
else
cout<<"\nElement "<<toFind<<" was found at position no. "<<result+1;
return 0;
}