-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathMin_Diff_Element.cpp
More file actions
52 lines (40 loc) · 939 Bytes
/
Min_Diff_Element.cpp
File metadata and controls
52 lines (40 loc) · 939 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
/*
Given a sorted array and a key
Find the element from the sorted array such that the difference of key and given element is minimum
*/
#include<iostream>
using namespace std;
int MinimumDiff(int arr[], int n, int target)
{
int start = 0;
int end = n-1;
int mid = start + (end-start)/2;
while(start<end)
{
mid = start + (end-start)/2;
if(arr[mid]<=target) start = mid;
else end = mid-1;
}
int lower = start;
start = 0;
end = n-1;
mid = start + (end-start)/2;
while(start<end)
{
mid = start + (end-start)/2;
if(arr[mid]<target) start = mid+1;
else end = mid;
}
int upper = start;
if(abs(target-arr[lower]) < abs(target - arr[upper]))
return lower;
else
return upper;
return -1;
}
int main()
{
int arr[] = {4,6,10,11};
cout<<MinimumDiff(arr,4,7);
return 0;
}