# Python | Sort an array according to absolute difference

Given an array of **N** distinct elements and a number **val**, rearrange the array elements according to the absolute difference with **val**, i. e., element having minimum difference comes first and so on. Also the order of array elements should be maintained in case two or more elements have equal differences.

Examples:

Input:val = 6, a = [7, 12, 2, 4, 8, 0]

Output:a = [7 4 8 2 12 0]Explanation:

Consider the absolute difference of each array element and ‘val’

7 – 6 = 1

12- 6 = 6

2 – 6 = 4 (abs)

4 – 6 = 2 (abs)

8 – 6 = 2

0 – 6 = 6 (abs)

So, according to the obtained differences, sort the array differences in increasing order,

1, 2, 2, 4, 6, 6 is obtained, and their corresponding array elements are 7, 4, 8, 2, 12, 0.

Input:val = -2, a = [5, 2, 0, -4]

Output:a = [0 -4 2 5]

**Approach: ** Normally a dictionary in Python can hold only one value corresponding to a key. But in this problem we may have to store multiple values for a particular key. Clearly, simple dictionary cannot be used, we need something like a multimap in C++. So, here Default dictionary is use, which works as Multimap in Python. Following are the steps to solve the problem.

- Store values in dictionary, where key is absolute difference between ‘val’ and array elements (i.e. abs(val-a[i])) and value is array elements (i.e. a[i])
- In multiimap, the values will be already in sorted order according to key because it implements self-balancing-bianry-search-tree internally.
- Update the values of original array by storing the dictionary elements one by one.

Below is the implementation of the above approach.

`# Python program to sort the array ` `# according to a value val ` ` ` `# Using Default dictionary (works as Multimap in Python) ` `from` `collections ` `import` `defaultdict ` `def` `rearrange(a, n, val): ` ` ` `# initialize Default dictionary ` ` ` `dict` `=` `defaultdict(` `list` `) ` ` ` ` ` `# Store values in dictionary (i.e. multimap) where, ` ` ` `# key: absolute difference between 'val' ` ` ` `# and array elements (i.e. abs(val-a[i])) and ` ` ` `# value: array elements (i.e. a[i]) ` ` ` `for` `i ` `in` `range` `(` `0` `, n): ` ` ` `dict` `[` `abs` `(val` `-` `a[i])].append(a[i]) ` ` ` ` ` `index ` `=` `0` ` ` ` ` `# Update the values of original array ` ` ` `# by storing the dictionary elements one by one ` ` ` `for` `i ` `in` `dict` `: ` ` ` ` ` `pos ` `=` `0` ` ` `while` `(pos<` `len` `(` `dict` `[i])): ` ` ` `a[index]` `=` `dict` `[i][pos] ` ` ` `index` `+` `=` `1` ` ` `pos` `+` `=` `1` ` ` `# Driver code ` `a ` `=` `[` `7` `, ` `12` `, ` `2` `, ` `4` `, ` `8` `, ` `0` `] ` `val ` `=` `6` ` ` `# len(a) gives the length of the list ` `rearrange(a, ` `len` `(a), val) ` ` ` `# print the modified final list ` `for` `i ` `in` `a: ` ` ` `print` `(i, end ` `=` `' '` `) ` |

*chevron_right*

*filter_none*

**Output:**

7 4 8 2 12 0

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

**Auxiliary Space:** O(N)

**Alternative Approach:** Use a 2-D matrix of size n*2 to store the absoulte difference and index at (i, 0) and (i, 1). Sort the 2-D matrix. According to the inbuilt matrix property, the matrix gets sorted in terms of first element, and if the first element is same, it gets sorted according to the second element. Get the index and print the array element accordingly.

Below is the implementation of above approach.

`def` `printsorted(a, n, val): ` ` ` ` ` `# declare a 2-D matrix ` ` ` `b ` `=` `[[` `0` `for` `x ` `in` `range` `(` `2` `)] ` `for` `y ` `in` `range` `(n)] ` ` ` ` ` `for` `i ` `in` `range` `(` `0` `, n): ` ` ` `b[i][` `0` `] ` `=` `abs` `(a[i]` `-` `val) ` ` ` `b[i][` `1` `] ` `=` `i ` ` ` ` ` ` ` `b.sort() ` ` ` ` ` `for` `i ` `in` `range` `(` `0` `, n): ` ` ` `print` `a[b[i][` `1` `]], ` ` ` ` ` ` ` `a ` `=` `[` `7` `, ` `12` `, ` `2` `, ` `4` `, ` `8` `, ` `0` `] ` `n ` `=` `len` `(a) ` `val ` `=` `6` `printsorted(a, n, val) ` |

*chevron_right*

*filter_none*

**Output:**

7 4 8 2 12 0

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

**Auxiliary Space:** O(N)

## Recommended Posts:

- Sort an array according to absolute difference with given value
- Sort an array according to absolute difference with a given value "using constant extra space"
- Maximum sum of absolute difference of an array
- Triplets in array with absolute difference less than k
- Absolute Difference of even and odd indexed elements in an Array
- k-th smallest absolute difference of two elements in an array
- Sum of minimum absolute difference of each array element
- 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
- Minimum absolute difference of adjacent elements in a circular array
- Minimum sum of absolute difference of pairs of two arrays
- Maximum absolute difference of value and index sums
- Maximum absolute difference between sum of two contiguous sub-arrays
- Minimum absolute difference of XOR values of two subarrays
- Find maximum number of elements such that their absolute difference is less than or equal to 1

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.