# Sort an array according to absolute difference with given value

Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, 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.

Examples :

Input :arr[] : 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}Input :x = 5, arr[] = {2, 6, 8, 3}Output :arr[] = {6, 3, 2, 8}

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

**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.

- 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 array with the values of map so that array has the required output.

## 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; ` ` ` `rearrange(arr, n, x); ` ` ` `printArray(arr, n); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## 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` `; ` ` ` `rearrange(arr, n, x); ` ` ` `printArray(arr, n); ` ` ` `} ` `} ` ` ` `// This code is contributed by rachana soma ` |

*chevron_right*

*filter_none*

**Output:**

5 9 10 3 2

**Time Complexity :** O(n Log n)

**Auxiliary Space : **O(n)

This article is contributed by **Sahil Chhabra**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: **DSA Self Paced**. Become industry ready at a student-friendly price.

## Recommended Posts:

- Python | Sort an array according to absolute difference
- Sort an array according to absolute difference with given value using Functors
- Sort an Array based on the absolute difference of adjacent elements
- Sort an array according to absolute difference with a given value "using constant extra space"
- Sort array such that absolute difference of adjacent elements is in increasing order
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Count elements in first Array with absolute difference greater than K with an element in second Array
- Triplets in array with absolute difference less than k
- Count pairs in an array such that the absolute difference between them is ≥ K
- k-th smallest absolute difference of two elements in an array
- Sum of minimum absolute difference of each array element
- Absolute Difference of even and odd indexed elements in an Array
- Array value by repeatedly replacing max 2 elements with their absolute difference
- Maximise sum of absolute difference between adjacent elements in Array with sum K
- Check if array can be divided into two sub-arrays such that their absolute difference is K
- Absolute Difference of all pairwise consecutive elements in an array
- Count pairs in an array whose absolute difference is divisible by K
- Maximum absolute difference between distinct elements in an Array
- Minimum absolute difference of adjacent elements in a circular array
- Find K elements whose absolute difference with median of array is maximum