Open In App

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

Last Updated : 30 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

Sort an array according to absolute difference with given value using Functors
Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., the element having a minimum difference comes first and so on. Note: If two or more elements are at equal distance arrange them in same sequence as in the given array. Examples: Input : x = 7, arr[] = {10, 5, 3, 9, 2} Out
6 min read
Sort an array according to absolute difference with given value
Given an array of N distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., an element having minimum difference comes first, and so on. Note: If two or more elements are at equal distances arrange them in the same sequence as in the given array. Examples: Input: x = 7, arr[] = {10, 5, 3, 9, 2}Ou
10 min read
K'th Largest element in BST using constant extra space
Given a binary search tree, task is to find Kth largest element in the binary search tree. Example: Input : k = 3 Root of following BST 10 / \ 4 20 / / \ 2 15 40 Output : 15 The idea is to use Reverse Morris Traversal which is based on Threaded Binary Trees. Threaded binary trees use the NULL pointers to store the successor and predecessor informat
10 min read
Connect nodes at same level using constant extra space
Write a function to connect all the adjacent nodes at the same level in a binary tree. The structure of the given Binary Tree node is like following C/C++ Code struct node{ int data; struct node* left; struct node* right; struct node* nextRight; }; // This code is contributed by Yash Agarwal(yashagarwal2852002) C/C++ Code struct node { int data; st
33 min read
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
Given a string representing a number, we need to get the sum of all possible sub strings of this string. Examples : Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23Recommended PracticeSum of all substrings of a numberTry It! We have discussed a solution
7 min read
Merge two BSTs with constant extra space
Given two Binary Search Trees(BST), print the elements of both BSTs in sorted form. Note: Both the BSTs will not have any common element. Examples: Input First BST: 3 / \ 1 5 Second BST: 4 / \ 2 6 Output: 1 2 3 4 5 6 Input: First BST: 8 / \ 2 10 / 1 Second BST: 5 / 3 / 0 Output: 0 1 2 3 5 8 10 The idea is to use the fact the leftmost element (first
31 min read
Rearrange positive and negative numbers with constant extra space
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained. Examples: Input: [12 11 -13 -5 6 -7 5 -3 -6] Output: [-13 -5 -7 -3 -6 12 11 6 5]R
34 min read
Move all negative numbers to beginning and positive to end with constant extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers. Examples : Input: -12, 11, -13, -5, 6, -7, 5, -3, -6Output: -12 -13 -5 -7 -3 -6 11 6 5 Note: Order of elements is not important here. Naive approach: The idea is to sort the array of ele
21 min read
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 differences. Examples: Input: val = 6, a = [7, 12, 2, 4, 8,
3 min read
Sort a binary array using one traversal and no extra space
Given a binary array, sort it using one traversal and no extra space Examples: Input: 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 1 0 0 Output: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1Explanation: The output is a sorted array of 0 and 1 Input: 1 0 1 0 1 0 1 0 Output: 0 0 0 0 1 1 1 1Explanation: The output is a sorted array of 0 and 1 Sort a binary array u
10 min read
Article Tags :
Practice Tags :