Sort an array according to absolute difference with a given value “using constant extra space”

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++
Java
Python 3
C#
PHP
Javascript
// 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 arrayvoid print(int arr[], int n){    for (int i = 0; i < n; i++)        cout << arr[i] << " ";} // Main Functionint 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 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 arraystatic void print(int arr[], int n){    for (int i = 0; i < n; i++)    System.out.print(arr[i] + " ");} // Driver codepublic 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 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 arraydef print_1(arr, n):     for i in range(n):        print(arr[i], end = " ") # Driver Codeif __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# 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 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 arrayfunction 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?>
<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)This article is contributed by Rohit Rao. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
Akanksha_Rai
princiraj1992
29AjayKumar
avanitrachhadiya2155
Insertion Sort
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Segregate 0s and 1s in an array
Sorting in Java
Find whether an array is subset of another array
Quick Sort vs Merge Sort
Stability in sorting algorithms
Find all triplets with zero sum