Python | Sort an array according to absolute difference
Last Updated :
30 Aug, 2022
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-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.
Python3
# 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 =' ')
Complexity Analysis:
- 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.
Implementation:
Python
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)
Complexity Analysis:
- Time Complexity: O(N * Log N)
Auxiliary Space: O(N)
Similar Reads
Sort an Array based on the absolute difference of adjacent elements Given an array arr[] containing N integers, the task is to rearrange all the elements of array such that absolute difference between consecutive elements of the array are sorted in increasing order.Examples Input: arr[] = { 5, -2, 4, 8, 6, 5 } Output: 5 5 6 4 8 -2 Explanation: |5 - 5| = 0 |5 - 6| =
7 min read
Sort an array according to absolute difference with a given value "using constant extra space" 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, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as
7 min read
Sum of minimum absolute differences in an array Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
7 min read
k-th smallest absolute difference of two elements in an array We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] - a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) as the smallest absolute difference among all these pairs. Examples:
9 min read
Python Program to Sort an array of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last. Examples: Input : {0, 1, 2, 0, 1, 2, 2, 2, 2, 1} Output : {0, 0, 1, 1, 1, 2, 2, 2, 2, 2} Input : {0, 1, 1, 0, 1, 2, 1, 2, 0,
2 min read
Find all pairs in an Array in sorted order with minimum absolute difference Given an integer array arr[] of size N, the task is to find all distinct pairs having minimum absolute difference and print them in ascending order. Examples:Input: arr[] = {4, 2, 1, 3}Output: {1, 2}, {2, 3}, {3, 4}Explanation: The minimum absolute difference between pairs is 1.Input: arr[] = {1, 3,
9 min read
Maximize the absolute difference for all elements in the array Given an array A[] of size N and B[] of size M (M >= N), the task is to construct an array C[] by choosing N integers from B[] such that for every index i, sum of absolute difference between A[i] and C[i] is maximum. Examples: Input: N = 4, M = 6, A[] = {6, 1, 2, 4}, B[] = {3, 5, 1, 7, 2, 3}Outpu
10 min read
Sum of absolute differences of all pairs in a given array Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array. Examples: Input : arr[] = {1, 2, 3, 4} Output: 10 Sum of |2-1| + |3-1| + |4-1| + |3-2| + |4-2| + |4-3| = 10 Input : arr[] = {1, 8, 9, 15, 16} Output: 74 Input : arr[]
11 min read
Absolute Difference of all pairwise consecutive elements in an array Given an array of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements. Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2 Examples: Input: arr[] = {8, 5, 4, 3, 15, 20}Output: 3, 1, 1, 12, 5I
4 min read