Python | Sort an array according to absolute difference

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 = 112- 6 = 62 – 6 = 4 (abs)4 – 6 = 2 (abs)8 – 6 = 20 – 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-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 defaultdictdef 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 listrearrange(a, len(a), val)  # print the modified final listfor i in a:     print(i, end =' ')  
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 = 6printsorted(a, n, val) 
7 4 8 2 12 0

Time Complexity: O(N * Log N)Auxiliary Space: O(N)
Akanksha_Rai
nidhi_biet
Python dictionary-programs
python-dict
Sorting Quiz
Arrays
Sorting
python-dict
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subarrays with average K
Introduction to Data Structures
Window Sliding Technique
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Next Greater Element
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm