📌  相关文章
📜  根据与元素 K 的距离对数组中的整数进行排序

📅  最后修改于: 2021-09-06 11:34:29             🧑  作者: Mango

给定一个由 N 个整数组成的数组 arr[]和一个整数 K ,任务是根据它们与给定整数K的距离对这些整数进行排序。如果超过1 个元素位于相同的距离,则按升序打印它们。
注意:数组中两个元素之间的距离是通过它们的索引之间的差异来衡量的。
注意:整数 K 始终存在于数组arr[] 中并且是唯一的
例子:

方法 :
为了解决上面提到的问题,我们创建了一个辅助向量来存储距离 K 任意距离的元素。然后找到给定整数 K 在数组 arr[] 中的位置,并将元素 K 插入到辅助向量中的位置 0 处。从 K 向左遍历数组,并将这些元素插入向量中与 K 的距离处。对 K 的右侧元素重复上述过程。最后,按排序顺序打印距离为 0 的数组元素。
下面是上述方法的实现:

C++
// C++ implementation to Sort the integers in
// array according to their distance from given
// element K present in the array
#include 
using namespace std;
 
// Function to get sorted array based on
// their distance from given integer K
void distanceSort(int arr[], int K, int n)
{
    // Vector to store respective elements
    // with their distance from integer K
    vector 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 distnce 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 code
int 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 array
import 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 distnce 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 Code
public 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 K
def 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 distnce 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 code
if __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 array
using System;
using System.Collections.Generic;
class GFG{
     
// Function to get sorted array based on
// their distance from given integer K
static void distanceSort(int []arr,
                         int K, int n)
{   
    // List to store respective elements
    // with their distance from integer K
    List []vd = new List[n];
    int i ;
    for(i = 0; i < n; i++)
    {
        vd[i] = new List();
    }
     
    // 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 distnce 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 Code
public 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


输出:
35 0 10 1101 14



时间复杂度: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live