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.
There should be a space between each element but no space or newline at the end of the output sequence.
#include<stdio.h>
#define MAXSIZE 20
/*
  Write a function for printing 5 closest numbers
*/
void printclosest(int arr[], int num, int n){
    int size,i,j,k,l,temp,key,dif[6],fi[6],dift[6];
  key=num;
  size=n;
   for(i=0;i<6;i++){
        dif[i]=10000;
        dift[i]=10000;
        fi[i]=0;
    }
    for(i=0;i<size;i++){
        if((arr[i]-key)<0){
            temp=key-arr[i];
           for(j=0;j<6;j++){
            if(dif[j]>temp){
                for(k=0;j+k<6;k++){
                    dif[5-k]=dif[5-k-1];
                    dift[5-k]=dift[5-k-1];
                }
                dif[j]=temp;
                dift[j]=-temp;
                break;
            }
           }
        }else{
            temp=arr[i]-key;
           for(j=0;j<6;j++){
            if(dif[j]>temp){
                for(k=0;j+k<5;k++){
                    dif[5-k]=dif[5-k-1];
                    dift[5-k]=dift[5-k-1];
                }
                dif[j]=temp;
                if(dift[j-1]==-temp){
                    dift[j-1]=temp;
                    dift[j]=-temp;
                }else{
                dift[j]=temp;
                }
                break;
            }
           }
        }
        }
    for(j=0;j<5;j++){
        printf("%d",key+dift[j]);
      if(j!=4)
        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;
}

 
No comments:
Post a Comment