Sort integers in array according to their distance from the element K

Given an array arr[] of N integers and an integer K, the task is to sort these integers according to their distance from given integer K. If more than 1 element is at the same distance, print them in increasing order.
Note: Distance between two elements in the array is measured as the difference between their index.
Note: The integer K is always present in array arr[] and is unique.
Examples:Â Â
Input: arr[] = {12, 10, 102, 31, 15}, K = 102Â
Output: 102 10 31 12 15Â
Explanation:Â
Elements at their respective distance from K are,Â
At distance 0: 102Â
At distance 1: 10, 31 in sorted form.Â
At distance 2: 12, 15 in sorted form.Â
Hence, our resultant array is [ 102, 10, 31, 12, 15 ]Input: arr[] = {14, 1101, 10, 35, 0}, K = 35Â
Output: 35 0 10 1101 14Â
Explanation:Â
Elements at their respective distance from K are,Â
At distance 0: 35Â
At distance 1: 10, 0 and in sorted form we have 0, 10.Â
At distance 2: 1101Â
At distance 3: 14Â
Hence, our resultant array is [ 35, 0, 10, 1101, 14 ]Â
Â
Approach :
To solve the problem mentioned above we create an auxiliary vector to store elements at any distance from K. Then find the position of given integer K in the array arr[] and insert the element K at position 0 in the auxiliary vector. Traverse the array in the left direction from K and insert those elements in the vector at their distance from K. Repeat the above process for the right side elements of K. Finally, print the array elements from distance 0 in sorted order.
Below is the implementation of the above approach:Â Â
C++
// C++ implementation to Sort the integers in// array according to their distance from given// element K present in the array#include <bits/stdc++.h>using namespace std;Â
// Function to get sorted array based on// their distance from given integer Kvoid distanceSort(int arr[], int K, int n){    // Vector to store respective elements    // with their distance from integer K    vector<int> vd[n];Â
    // Find the position of integer K    int pos;Â
    for (int i = 0; i < n; i++) {        if (arr[i] == K) {            pos = i;            break;        }    }Â
    // Insert the elements with their    // distance from K in vectorÂ
    int i = pos - 1, j = pos + 1;Â
    // Element at distance 0    vd[0].push_back(arr[pos]);Â
    // Elements at left side of K    while (i >= 0) {        vd[pos - i].push_back(arr[i]);        --i;    }Â
    // Elements at right side of K    while (j < n) {        vd[j - pos].push_back(arr[j]);        ++j;    }Â
    // Print the vector content in sorted order    for (int i = 0; i <= max(pos, n - pos - 1); ++i) {Â
        // Sort elements at same distance        sort(begin(vd[i]), end(vd[i]));Â
        // Print elements at distance i from K        for (auto element : vd[i])            cout << element << " ";    }}Â
// Driver codeint main(){Â Â Â Â int arr[] = {14, 1101, 10, 35, 0 }, K = 35;Â
    int n = sizeof(arr) / sizeof(arr[0]);Â
    distanceSort(arr, K, n);Â
    return 0;} |
Java
// Java implementation to Sort the integers in// array according to their distance from given// element K present in the arrayimport java.util.*;Â
class GFG{     // Function to get sorted array based on// their distance from given integer K@SuppressWarnings("unchecked")static void distanceSort(int arr[], int K, int n){         // Vector to store respective elements    // with their distance from integer K    Vector vd[] = new Vector[n];         for(int i = 0; i < n; i++)    {        vd[i] = new Vector();    }         // Find the position of integer K    int pos = 0;      for(int i = 0; i < n; i++)     {        if (arr[i] == K)        {            pos = i;            break;        }    }      // Insert the elements with their    // distance from K in vector    int i = pos - 1, j = pos + 1;      // Element at distance 0    vd[0].add(arr[pos]);      // Elements at left side of K    while (i >= 0)    {        vd[pos - i].add(arr[i]);        --i;    }      // Elements at right side of K    while (j < n)    {        vd[j - pos].add(arr[j]);        ++j;    }      // Print the vector content in sorted order    for(i = 0; i <= Math.max(pos, n - pos - 1); ++i)    {                 // Sort elements at same distance        Collections.sort(vd[i]);          // Print elements at distance i from K        for (j = 0; j < vd[i].size(); j++)        {            int element = (int)vd[i].get(j);            System.out.print(element + " ");        }    }}     // Driver Codepublic static void main(String s[]){    int arr[] = {14, 1101, 10, 35, 0 };    int K = 35;Â
    int n = arr.length;Â
    distanceSort(arr, K, n);}   }Â
// This code is contributed by rutvik_56 |
Python3
# Python3 implementation to Sort the integers in# array according to their distance from given# element K present in the arrayÂ
# Function to get sorted array based on# their distance from given integer Kdef distanceSort(arr,K,n):    # Vector to store respective elements    # with their distance from integer K    vd = [[] for i in range(n)]Â
    # Find the position of integer KÂ
    for i in range(n):        if (arr[i] == K):            pos = i            breakÂ
    # Insert the elements with their    # distance from K in vectorÂ
    i = pos - 1    j = pos + 1Â
    # Element at distance 0    vd[0].append(arr[pos])Â
    # Elements at left side of K    while (i >= 0):        vd[pos - i].append(arr[i])        i -= 1Â
    # Elements at right side of K    while (j < n):        vd[j - pos].append(arr[j])        j += 1Â
    # Print the vector content in sorted order    for i in range(max(pos, n - pos - 1) + 1):Â
        # Sort elements at same distance        vd[i].sort(reverse=False)Â
        # Print elements at distance i from K        for element in vd[i]:            print(element,end = " ")Â
# Driver codeif __name__ == '__main__':Â Â Â Â arr =Â [14, 1101, 10, 35, 0]Â Â Â Â K = 35Â
    n = len(arr)Â
    distanceSort(arr, K, n)Â
# This code is contributed by Surendra_Gangwar |
C#
// C# implementation to Sort the integers in// array according to their distance from given// element K present in the arrayusing System;using System.Collections.Generic;class GFG{     // Function to get sorted array based on// their distance from given integer Kstatic void distanceSort(int []arr,                          int K, int n){       // List to store respective elements    // with their distance from integer K    List<int> []vd = new List<int>[n];    int i ;    for(i = 0; i < n; i++)    {        vd[i] = new List<int>();    }         // Find the position of integer K    int pos = 0;      for(i = 0; i < n; i++)     {        if (arr[i] == K)        {            pos = i;            break;        }    }      // Insert the elements with their    // distance from K in vector    int j = pos + 1;     i = pos - 1;       // Element at distance 0    vd[0].Add(arr[pos]);      // Elements at left side of K    while (i >= 0)    {        vd[pos - i].Add(arr[i]);        --i;    }      // Elements at right side of K    while (j < n)    {        vd[j - pos].Add(arr[j]);        ++j;    }      // Print the vector content in sorted order    for(i = 0; i <= Math.Max(pos,                              n - pos - 1); ++i)    {               // Sort elements at same distance        vd[i].Sort();          // Print elements at distance i from K        for (j = 0; j < vd[i].Count; j++)        {            int element = (int)vd[i][j];            Console.Write(element + " ");        }    }}     // Driver Codepublic static void Main(String []args){    int []arr = {14, 1101, 10, 35, 0};    int K = 35;    int n = arr.Length;    distanceSort(arr, K, n);}   }Â
// This code is contributed by shikhasingrajput |
Javascript
<script>Â
// JavaScript implementation to Sort the integers in// array according to their distance from given// element K present in the arrayÂ
// Function to get sorted array based on// their distance from given integer Kfunction distanceSort(arr, K, n){Â
    // Vector to store respective elements    // with their distance from integer K    let vd = new Array(n);    for(let i = 0; i < n; i++)    {        vd[i] = new Array();    }Â
    // Find the position of integer K    for(let i = 0; i < n; i++)    {        if (arr[i] == K)        {            pos = i            break        }    }Â
    // Insert the elements with their    // distance from K in vectorÂ
    let i = pos - 1    let j = pos + 1Â
    // Element at distance 0    vd[0].push(arr[pos])Â
    // Elements at left side of K    while (i >= 0){        vd[pos - i].push(arr[i])        i -= 1    }Â
    // Elements at right side of K    while (j < n){        vd[j - pos].push(arr[j])        j += 1    }Â
    // Print the vector content in sorted order    for(let i = 0;i< Math.max(pos, n - pos - 1) + 1;i++){Â
        // Sort elements at same distance        vd[i].sort()Â
        // Print elements at distance i from K        for(let element of vd[i])            document.write(element," ")    }}Â
// Driver codeÂ
let arr =Â [14, 1101, 10, 35, 0]let K = 35Â
let n = arr.lengthÂ
distanceSort(arr, K, n)Â
// This code is contributed by ShinjanpatraÂ
</script> |
35 0 10 1101 14
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


