Skip to content
Related Articles
Python | Sort an array according to absolute difference
• Difficulty Level : Medium
• Last Updated : 11 Oct, 2019

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]

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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-binary-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 ``=``' '``)  `
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 absolute 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) `
Output:
```7 4 8 2 12 0
```

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up