Open In App

Sort an array according to absolute difference with given value

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of N distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., an element having minimum difference comes first, and so on. 
Note: If two or more elements are at equal distances arrange them in the same sequence as in the given array.

Examples:

Input: x = 7, arr[] = {10, 5, 3, 9, 2}
Output: arr[] = {5, 9, 10, 3, 2}
Explanation:
7 – 10 = 3(abs)
7 – 5 = 2
7 – 3 = 4 
7 – 9 = 2(abs)
7 – 2 = 5
So according to the difference with X, 
elements are arranged as 5, 9, 10, 3, 2.

Input: x = 6, arr[] = {1, 2, 3, 4, 5}   
Output: arr[] = {5, 4, 3, 2, 1}

Recommended Practice

Sort an array according to absolute difference with a given value using self-balancing BST:

To solve the problem follow the below idea:

The idea is to use a self-balancing binary search tree. We traverse the input array and for every element, we find its difference with x and store the difference as key and element as the value in a self-balancing binary search tree. Finally, we traverse the tree and print its inorder traversal which is the required output.

Approach for C++ Implementation: 

In C++, self-balancing-binary-search-tree is implemented by set, map, and multimap. We can’t use set here as we have key-value pairs (not only keys). We also can’t directly use map also as a single key can belong to multiple values and map allows a single value for a key. So we use multimap which stores key-value pairs and can have multiple values for a key.

Follow the below steps to solve the problem:

  • Store the values in the multimap with the difference with X as key.
  • In multimap, the values will be already in sorted order according to key i.e. difference with X because it implements self-balancing-binary-search-tree internally.
  • Update all the values of an array with the values of the map so that the array has the required output.

Below is the implementation of the above approach:

C++




// C++ program to sort an array according absolute
// difference with x.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort an array according absolute
// difference with x.
void rearrange(int arr[], int n, int x)
{
    multimap<int, int> m;
    multimap<int, int>::iterator it;
    // Store values in a map with the difference
    // with X as key
    for (int i = 0; i < n; i++)
        m.insert(make_pair(abs(x - arr[i]), arr[i]));
 
    // Update the values of array
    int i = 0;
    for (it = m.begin(); it != m.end(); it++)
        arr[i++] = (*it).second;
}
 
// Function to print the array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 10, 5, 3, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
 
    // Function call
    rearrange(arr, n, x);
    printArray(arr, n);
    return 0;
}


Java




// Java program to sort an array according absolute
// difference with x.
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to sort an array according absolute
    // difference with x.
    static void rearrange(int[] arr, int n, int x)
    {
        TreeMap<Integer, ArrayList<Integer> > m
            = new TreeMap<>();
 
        // Store values in a map with the difference
        // with X as key
        for (int i = 0; i < n; i++) {
            int diff = Math.abs(x - arr[i]);
            if (m.containsKey(diff)) {
                ArrayList<Integer> al = m.get(diff);
                al.add(arr[i]);
                m.put(diff, al);
            }
            else {
                ArrayList<Integer> al = new ArrayList<>();
                al.add(arr[i]);
                m.put(diff, al);
            }
        }
 
        // Update the values of array
        int index = 0;
        for (Map.Entry entry : m.entrySet()) {
            ArrayList<Integer> al = m.get(entry.getKey());
            for (int i = 0; i < al.size(); i++)
                arr[index++] = al.get(i);
        }
    }
 
    // Function to print the array
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] arr = { 10, 5, 3, 9, 2 };
        int n = arr.length;
        int x = 7;
 
        // Function call
        rearrange(arr, n, x);
        printArray(arr, n);
    }
}
 
// This code is contributed by rachana soma


Python3




# Python3 program to sort an
# array according absolute
# difference with x.
 
# Function to sort an array
# according absolute difference
# with x.
 
 
def rearrange(arr, n, x):
 
    m = {}
 
    # Store values in a map
    # with the difference
    # with X as key
    for i in range(n):
        m[arr[i]] = abs(x - arr[i])
 
    m = {k: v for k, v in sorted(m.items(),
                                 key=lambda item: item[1])}
 
    # Update the values of array
    i = 0
 
    for it in m.keys():
        arr[i] = it
        i += 1
 
# Function to print the array
 
 
def printArray(arr, n):
 
    for i in range(n):
        print(arr[i], end=" ")
 
 
# Driver code
if __name__ == "__main__":
 
    arr = [10, 5, 3, 9, 2]
    n = len(arr)
    x = 7
 
    # Function call
    rearrange(arr, n, x)
    printArray(arr, n)
 
# This code is contributed by Chitranayal


C#




// C# program to sort an array according absolute
// difference with x.
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to sort an array according absolute
    // difference with x.
    static void rearrange(int[] arr, int n, int x)
    {
        SortedDictionary<int, List<int> > m
            = new SortedDictionary<int, List<int> >();
 
        // Store values in a map with the difference
        // with X as key
        for (int i = 0; i < n; i++) {
            int diff = Math.Abs(x - arr[i]);
            if (m.ContainsKey(diff)) {
                List<int> al = m;
                al.Add(arr[i]);
                m = al;
            }
            else {
                List<int> al = new List<int>();
                al.Add(arr[i]);
                m.Add(diff, al);
            }
        }
        // Update the values of array
        int index = 0;
        foreach(int entry in m.Keys)
        {
            List<int> al = m[entry];
            for (int i = 0; i < al.Count; i++)
                arr[index++] = al[i];
        }
    }
 
    // Function to print the array
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = { 10, 5, 3, 9, 2 };
        int n = arr.Length;
        int x = 7;
 
        // Function call
        rearrange(arr, n, x);
        printArray(arr, n);
    }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript




// JavaScript program to sort an array according absolute
// difference with x.
 
// Function to sort an array according absolute
// difference with x.
function rearrange(arr,n,x)
{
    let m = new Map();
     
    // Store values in a map with the difference
            // with X as key
            for (let i = 0; i < n; i++)
            {
                m.set(arr[i],Math.abs(x-arr[i]));
            }
              
            let m1 = new Map([...m.entries()].sort((a, b) =>
            a[1] - b[1]));
             
            // Update the values of array
            let index = 0;
            for (let [key, value] of m1.entries())
            {
                arr[index++] =key
            }
}
 
// Function to print the array
function printArray(arr,n)
{
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}
 
// Driver code
let arr=[10, 5, 3, 9 ,2];
let n = arr.length;
let x = 7;
rearrange(arr, n, x);
printArray(arr, n);
 
// This code is contributed by ab2127


Output

5 9 10 3 2 

Time Complexity: O(N Log N) 
Auxiliary Space: O(N)

 

Sort an array according to absolute difference with a given value using C++ STL:

In C++, we can use stable_sort(), and write a lambda expression for the custom comparator function. This solution is elegant and far easier to understand. The only challenge in writing the lambda expression is to send the value ‘x’ into the lambda expression to be able to use it inside the expression. This can be achieved either by operator overloading with the help of a class or using a much simpler capture.

Below is the implementation of the above approach:

C++




// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void rearrange(int arr[], int n, int x)
{
    /*
        We can send the value x into
        lambda expression as
        follows: [capture]()
        {
            //statements
            //capture value can be used inside
        }
    */
    stable_sort(arr, arr + n, [x](int a, int b) {
        if (abs(a - x) < abs(b - x))
            return true;
        else
            return false;
    });
}
 
// Driver code
int main()
{
    int arr[] = { 10, 5, 3, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
   
      // Function call
    rearrange(arr, n, x);
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
class GFG {
  static List<Integer> rearrange(List<Integer> arr, int n,
                                 int x)
  {
    Collections.sort(
      arr,
      (a, b) -> Math.abs(x - a) - Math.abs(x - b));
    return arr;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    List<Integer> arr = new ArrayList<>();
    arr.add(10);
    arr.add(5);
    arr.add(3);
    arr.add(9);
    arr.add(2);
    int n = arr.size();
    int x = 7;
    // Function call
    arr = rearrange(arr, n, x);
    for (int num : arr) {
      System.out.print(num + " ");
    }
  }
}
 
// This code is contributed by phasing17.


Python3




# Python3 program for the above approach
def rearrange(arr, n, x):
 
    '''
        We can send the value x into
        lambda expression as
        follows: [capture]()
         
            #statements
            #capture value can be used inside
         
    '''
    arr.sort(key = lambda a: abs(a - x) )
     
# Driver code
arr = [ 10, 5, 3, 9, 2 ];
n = len(arr)
x = 7;
   
# Function call
rearrange(arr, n, x);
print(*arr)
 
# This code is contributed by phasing17


C#




// C# program for the above approach
 
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG
{
  static List<int> rearrange(List<int> arr, int n, int x)
  {
    /*
            We can send the value x into
            lambda expression as
            follows: [capture]()
            {
                //statements
                //capture value can be used inside
            }
        */
    return arr.OrderBy(a => Math.Abs(x - a)).ToList();
 
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    List<int> arr = new List<int>{10, 5, 3, 9, 2};
    int n = arr.Count;
    int x = 7;
 
    // Function call
    arr = rearrange(arr, n, x);
    foreach (int num in arr)
      Console.Write(num + " ");
  }
}
 
// This code is contributed by phasing17


Javascript




// JS program for the above approach
function rearrange(arr, n, x)
{
    /*
        We can send the value x into
        lambda expression as
        follows: [capture]()
        {
            //statements
            //capture value can be used inside
        }
    */
    arr.sort(function(a, b)
    {
        return Math.abs(a - x) - Math.abs(b - x)
    })
}
 
// Driver code
let arr = [ 10, 5, 3, 9, 2 ];
let n = arr.length
let x = 7;
   
// Function call
rearrange(arr, n, x);
console.log(arr.join(" "))
 
// This code is contributed by phasing17


Output

5 9 10 3 2 

Time Complexity: O(N log N)
Auxiliary Space: O(1)

This article is contributed by D. Mohit Varsha.



Last Updated : 03 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads