You are given a sorted list of N numbers and a number Num. Write a program to find the five numbers that are closest (numerically) to Num. A number x in the array is closest to Num if |Num-x| is the smallest among all such x possible.
Note: If the Num is present in given list, then it should be in the output.
Constraints:
5 < N <20
All numbers in list are between -10000 to 10000
-10000 <Num< 10000
There could be numbers that are repeated
Input:
N Num
m1 m2 m3 .. mN
where mi's are N numbers in sorted order.
Output:
p1 p2 p3 p4 p5
where pi's are closest numbers in increasing order of absolute difference from Num. If there are two numbers with same difference, print the larger one first.
There should be a space between each element but no space or newline at the end of the output sequence.
Implementation:
Note: If the Num is present in given list, then it should be in the output.
Constraints:
5 < N <20
All numbers in list are between -10000 to 10000
-10000 <Num< 10000
There could be numbers that are repeated
Input:
N Num
m1 m2 m3 .. mN
where mi's are N numbers in sorted order.
Output:
p1 p2 p3 p4 p5
where pi's are closest numbers in increasing order of absolute difference from Num. If there are two numbers with same difference, print the larger one first.
There should be a space between each element but no space or newline at the end of the output sequence.
Implementation:
#include<stdio.h>
#define MAXSIZE 20
/*
Write a function for printing 5 closest numbers
*/
int min(int x,int y)
{
if(x>y)
return x-y;
else
return y-x;
}
int findmin(int *a,int num,int n)
{
int i,min_val=min(num,*(a+0)),min_index=0;
for(i=1;i<n;i++)
{
if(min(num,a[i])<min_val)
{
min_val = min(num,a[i]);
min_index = i;
}
}
return min_index;
}
void printclosest(int arr[], int num, int n){
int index = findmin(arr,num,n);
int print=4;
int l=index-1;
int r=index+1;
printf("%d ",arr[index]);
while(print && l>=0 && r<n)
{
if(num-arr[l]<arr[r]-num)
{
printf("%d",arr[l--]);
}
else if(num-arr[l]>arr[r]-num)
{
printf("%d",arr[r++]);
}
else
{
if(arr[l]>arr[r])
printf("%d",arr[l--]);
else
printf("%d",arr[r++]);
}
print--;
if(print)
printf(" ");
}
while(print && l>=0)
{
printf("%d",arr[l--]);
print--;
if(print)
printf(" ");
}
while(print && r<n)
{
printf("%d ",arr[r++]);
print--;
if(print)
printf(" ");
}
}
int main()
{
int arr[MAXSIZE];
int i,n,num;
scanf("%d %d",&n,&num);
for (i = 0; i < n; ++i)
{
scanf("%d",&arr[i]);
}
printclosest(arr, num, n);
return 0;
}