forked from sauravgpt2/hacktoberfest36_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.cpp
37 lines (35 loc) · 885 Bytes
/
Binary_Search.cpp
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
//Binary Search->
#include <iostream>
using namespace std;
int main()
{
int n,i, num, first, last, middle;
cout<< "Enter the number of elements in array:\n";
cin>>n;
int arr[n];
cout<<"Enter the Elements (in ascending order): \n";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\nEnter Element to be Searched: ";
cin>>num;
first = 0;
last = n-1;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<num)
first = middle+1;
else if(arr[middle]==num)
{
cout<<"\nThe number "<<num<<" found at Position "<<middle+1<<" \nAnd at index "<<middle;
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
cout<<"\nThe number, "<<num<<" is not found in given Array";
cout<<endl;
return 0;
}