Sort an array according to absolute difference with a given value "using constant extra space"
Last Updated :
30 Apr, 2021
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 in the given array.
Examples:
Input : arr[] = {10, 5, 3, 9, 2}
x = 7
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 : arr[] = {1, 2, 3, 4, 5}
x = 6
Output : arr[] = {5, 4, 3, 2, 1}
The above problem has already been explained in a previous post here. It takes O(n log n) time and O(n) extra space. The below solution though has a relatively bad time complexity i.e O(n^2) but it does the work without using any additional space or memory.
The solution is a based on Insertion Sort . For every i (1<= i < n) we compare the absolute value of the difference of arr[i] with the given number x (Let this be 'diff' ). We then compare this difference with the difference of abs(arr[j]-x) where 0<= j < i (Let this if abdiff). If diff is greater than abdiff, we shift the values in the array to accommodate arr[i] in it's correct position.
C++
// C++ program to sort an array based on absolute
// difference with a given value x.
#include <bits/stdc++.h>
using namespace std;
void arrange(int arr[], int n, int x)
{
// Below lines are similar to insertion sort
for (int i = 1; i < n; i++) {
int diff = abs(arr[i] - x);
// Insert arr[i] at correct place
int j = i - 1;
if (abs(arr[j] - x) > diff) {
int temp = arr[i];
while (abs(arr[j] - x) > diff && j >= 0) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
}
// Function to print the array
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Main Function
int main()
{
int arr[] = { 10, 5, 3, 9, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 7;
arrange(arr, n, x);
print(arr, n);
return 0;
}
Java
// Java program to sort an array based on absolute
// difference with a given value x.
class GFG {
static void arrange(int arr[], int n, int x)
{
// Below lines are similar to insertion sort
for (int i = 1; i < n; i++) {
int diff = Math.abs(arr[i] - x);
// Insert arr[i] at correct place
int j = i - 1;
if (Math.abs(arr[j] - x) > diff)
{
int temp = arr[i];
while (j >= 0 && Math.abs(arr[j] - x) > diff)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
}
// Function to print the array
static void print(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;
arrange(arr, n, x);
print(arr, n);
}
}
// This code is contributed by PrinciRaj1992
Python 3
# Python 3 program to sort an array
# based on absolute difference with
# a given value x.
def arrange(arr, n, x):
# Below lines are similar to
# insertion sort
for i in range(1, n) :
diff = abs(arr[i] - x)
# Insert arr[i] at correct place
j = i - 1
if (abs(arr[j] - x) > diff) :
temp = arr[i]
while (abs(arr[j] - x) >
diff and j >= 0) :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = temp
# Function to print the array
def print_1(arr, n):
for i in range(n):
print(arr[i], end = " ")
# Driver Code
if __name__ == "__main__":
arr = [ 10, 5, 3, 9, 2 ]
n = len(arr)
x = 7
arrange(arr, n, x)
print_1(arr, n)
# This code is contributed by ita_c
C#
// C# program to sort an array based on absolute
// difference with a given value x.
using System;
class GFG
{
static void arrange(int []arr, int n, int x)
{
// Below lines are similar to insertion sort
for (int i = 1; i < n; i++)
{
int diff = Math.Abs(arr[i] - x);
// Insert arr[i] at correct place
int j = i - 1;
if (Math.Abs(arr[j] - x) > diff)
{
int temp = arr[i];
while (j >= 0 && Math.Abs(arr[j] - x) > diff)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
}
// Function to print the array
static void print(int []arr, int n)
{
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// Driver code
public static void Main()
{
int []arr = { 10, 5, 3, 9, 2 };
int n = arr.Length;
int x = 7;
arrange(arr, n, x);
print(arr, n);
}
}
// This code is contributed by 29AjayKumar
PHP
<?php
// PHP program to sort an array based on
// absolute difference with a given value x.
function arrange($arr, $n, $x)
{
// Below lines are similar to
// insertion sort
for ($i = 1; $i < $n; $i++)
{
$diff = abs($arr[$i] - $x);
// Insert arr[i] at correct place
$j = $i - 1;
if (abs($arr[$j] - $x) > $diff)
{
$temp = $arr[$i];
while (abs($arr[$j] - $x) >
$diff && $j >= 0)
{
$arr[$j + 1] = $arr[$j];
$j--;
}
$arr[$j + 1] = $temp;
}
}
return $arr;
}
// Function to print the array
function print_arr($arr, $n)
{
for ($i = 0; $i < $n; $i++)
echo $arr[$i] . " ";
}
// Driver Code
$arr = array(10, 5, 3, 9, 2);
$n = sizeof($arr);
$x = 7;
$arr1 = arrange($arr, $n, $x);
print_arr($arr1, $n);
// This code is contributed
// by Akanksha Rai
?>
JavaScript
<script>
// Javascript program to sort
// an array based on absolute
// difference with a given value x.
function arrange(arr,n,x)
{
// Below lines are similar
// to insertion sort
for (let i = 1; i < n; i++) {
let diff = Math.abs(arr[i] - x);
// Insert arr[i] at correct place
let j = i - 1;
if (Math.abs(arr[j] - x) > diff)
{
let temp = arr[i];
while (j >= 0 &&
Math.abs(arr[j] - x) > diff)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
}
// Function to print the array
function print(arr,n)
{
for (let i = 0; i < n; i++)
document.write(arr[i] + " ");
}
// Driver code
let arr=[10, 5, 3, 9, 2 ];
let n = arr.length;
let x = 7;
arrange(arr, n, x);
print(arr, n);
// This code is contributed
// by avanitrachhadiya2155
</script>
Output:
5 9 10 3 2
Time Complexity: O(n^2) where n is the size of the array.
Auxiliary Space: O(1)
Similar Reads
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 difference
3 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
Array element with minimum sum of absolute differences | Set 2 Given an array arr[] consisting of N positive integers, the task is to find an array element X such that sum of its absolute differences with every array element is minimum. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 3Explanation: For element arr[0](= 1): |(1 - 1)| + |(2 - 1)| + |(3 - 1)| + |(4
7 min read
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
Array value by repeatedly replacing max 2 elements with their absolute difference Given an array arr size N, the task is to print the final array value remaining in the array when the maximum and second maximum element of the array is replaced by their absolute difference in the array, repeatedly. Note: If the maximum two elements are same, then both are removed from the array, w
6 min read