-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryS2.cpp
52 lines (44 loc) · 924 Bytes
/
BinaryS2.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
using namespace std;
// Search Insert Position
int BinarySearch(int arr[], int n, int target)
{
// start, end, mid;
int start = 0, end = n-1, ans = n, mid;
while(start<=end)
{
// Mid ko find karo
mid = (start + end) / 2;
// arr[mid]==target
if(arr[mid]==target)
{
ans = mid;
break;
}
// arr[mid]<target
else if(arr[mid]<target)
start = mid + 1;
// arr[mid]>target
else
{
ans = mid;
end = mid - 1;
}
}
return ans;
}
int main()
{
int arr[1000];
int n;
cout<<"Enter the number element array: ";
cin>>n;
cout<<"Enter the elements: ";
for(int i=0; i<n; i++)
cin>>arr[i];
int target;
cout<<"Enter the target: ";
cin>>target;
cout<<BinarySearch(arr,n,target)<<endl;
return 0;
}