Sort by Absolute Difference | Practice | GeeksforGeeks

Given an array of N elements and a number K. The task is to arrange array elements according to the absolute difference with K, i. e., element having minimum difference comes first and so on.
Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.
 
Example 1:
Input: N = 5, K = 7
arr[] = {10, 5, 3, 9, 2}
Output: 5 9 10 3 2
Explanation: Sorting the numbers accoding to 
the absolute difference with 7, we have 
array elements as 5, 9, 10, 3, 2.
Example 2:
Input: N = 5, K = 6
arr[] = {1, 2, 3, 4, 5}
Output: 5 4 3 2 1
Explanation: Sorting the numbers according to 
the absolute difference with 6, we have array 
elements as 5 4 3 2 1.

Your Task:
This is a functional problem. You only need to complete the function sortABS(). The printing is done automatically by the driver code.

Expected Time Complexity: O(N log(N) ).
Expected Auxiliary Space: O(N).

Constraints:
1 <= N <= 105
1 <= K <= 105
 
0
vinay221120021 week ago
//c++ solution using vector-pair
void sortABS(int a[],int n, int k)
   {
       //Your code here
       int b[n];
       vector<pair<int,int>>ans(n);
       for(int i=0;i<n;i++)
       {
           b[i]=a[i];
           ans[i].first=abs(k-a[i]);
           ans[i].second=i;
       }
       sort(ans.begin(),ans.end());
       for(int i=0;i<n;i++)
       {
           a[i]=b[ans[i].second];
       }
   }
+2
prashan1um5l1 week ago
C++ Solution :
void sortABS(int A[],int N, int k)
    {
       stable_sort(A, A + N, [&k](int a, int b) -> bool {
           return abs(a - k) < abs(b - k);
       });
    }
    
0
kanishk2512961 week ago
    void sortABS(int arr[],int n, int k)
    {
       //Your code here
       stable_sort(arr,arr+n,[k](int a, int b){
           return(abs(k-a) < abs(k-b));
       });
    }
0
sonulamba2410342 weeks ago
can anyone check why my code is not working ??
i use pair for sorting 
 
 
 
for(int i=0; i<N; i++){           A[i]= A[i]-k;       }       bool check;       pair<int, bool> pa[N];       for(int i=0; i<N; i++){           if (A[i]>=0){               check = true;           }else{              check = false;           }           pa[i] = {abs(A[i]), check};       }              // i have to sort it           sort(pa, pa+N);       for(int i =0; i<N; i++){           if(pa[i].second == false){               A[i] = -1*(pa[i].first);               A[i] += k;           }           else{               A[i] = pa[i].first;               A[i] += k;           }       }
0
vii2sharma2 weeks ago
/*make differences as key in an unordered map 
and save the corresponding array elements as given in the array. now iterate from 0 to max difference and print the entire respective elements.  */
void sortABS(int A[],int N, int k)   {      //Your code here      // add your code here       unordered_map <int,vector<int>> m;       int maxDiff = INT_MIN;       for(int i =0;i<N;i++)       {           int diff = abs(k - A[i]);                      m[diff].push_back(A[i]);           maxDiff = (maxDiff > diff) ? maxDiff : diff;       }       vector<int> newarray;       for(int i = 0; i <= maxDiff; i++)       {           if(m.find(i) != m.end())           {               int k = 0;               while(k < m[i].size())               {                   newarray.push_back(m[i][k]);                   k++;               }           }       }                  for(int i = 0;i < N;i++)       {           A[i] = newarray[i];       }   }
+1
ankitmaurya32 weeks ago
def sortAbs(self,a, n, k):
        return sorted(a,key = lambda x : abs(x-k))
0
thakursahabsingh123 weeks ago
C++ Solution,
 
     class Solution{
    public:      // A[]: input array   // N: size of array   //Function to sort the array according to difference with given number.   void merge(int *A,int l , int mid , int r, int k){         int a1[r-l+1];   int p1=l , p2=mid+1,i=0;      while(p1<=mid && p2<=r){              if(abs(A[p1]-k)<abs(A[p2]-k))          a1[i++] = A[p1++];       else if(abs(A[p1]-k)>abs(A[p2]-k))          a1[i++] = A[p2++];       else{              if(p1<p2) a1[i++]=A[p1++];              else a1[i++] = A[p2++];          }          }      while(p1<=mid)a1[i++] = A[p1++];   while(p2<=r) a1[i++] = A[p2++];      i=0;   for(int j=l;j<=r;j++){       A[j] = a1[i++];   }      }
void mergeSort(int *A, int l , int r, int k){        if(l<r){                      int mid = l + (r - l)/2;                mergeSort(A,l,mid,k);        mergeSort(A,mid+1,r,k);        merge(A,l,mid,r,k);    }    }
 
   void sortABS(int A[],int N, int k)   {         mergeSort(A,0,N-1,k);   }}; 
0
vulture13023 weeks ago
//modifing merge sort  algo for the question
void mergeSort(int arr[],int l,int m,int h,int diff ){
        int n1=m-l+1;
        int n2=h-m;
        
        int left[n1];
        int right[n2];
        
        for(int i =0;i<n1;i++){
            left[i]=arr[i+l];
            
        }
        for(int j=0;j<n2;j++){
            right[j]=arr[m+1+j];
            
        }
        
        int i=0,j=0,k=l;
        
        while(i<n1&&j<n2){
            
            if(abs(left[i]-diff)<=abs(right[j]-diff)){
                arr[k++]=left[i++];
                
                
            }else{
                arr[k++]=right[j++];
            }
            
        }
        
        while(i<n1){
            arr[k++]=left[i++];
            
        }
        while(j<n2){
            
            arr[k++]=right[j++];
        }
        
        
        
        
    }
    
    void sort(int arr[],int l,int h,int k){
        int mid=l+(h-l)/2;
        
        if(l>=h){
            return;
            
        }
        
        sort(arr,l,mid,k);
        sort(arr,mid+1,h,k);
        mergeSort(arr,l,mid,h,k);
        
        
    }
    
    void sortABS(int arr[],int n, int k)
    {
        sort(arr,0,n-1,k);
        
        
       
    }

0
luyan04221 month ago
what's wrong with my code
void sortABS(int A[],int N, int k)
    {
       sort(A, A + N);
       int small[N] = {0};
       int big[N] = {0};
       int s = 0, b = 0;
       for(int i = 0; i < N; i++){ //創建兩個 array 
           if(A[i] <= k){
               small[s++] = A[i];
           }
           else{
               big[b++] = A[i];
           }
       }
       int i = s - 1, j = 0, a = 0;
       
       while(i > -1 && j < b){
           if((big[j] - k) > (k - small[i])){
               A[a++] = small[i--];
           }
           else if((big[j] - k) < (k - small[i])){
               A[a++] = big[j++];
           }
           else{
               A[a++] = small[i--];
               A[a++] = big[j++];
           }
       }
       
       while( i > -1){
           A[a++] = small[i--];
       }
       
       while(j < b){
           A[a++] = big[j++];
       }
    }

};
0
omprakashm20
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.