📌  相关文章
📜  根据相邻元素的绝对差对数组排序

📅  最后修改于: 2021-06-26 23:25:35             🧑  作者: Mango

给定包含N个整数的数组arr [] ,任务是重新排列数组的所有元素,以使数组连续元素之间的绝对差以递增顺序排序。

例子

方法:可以使用贪婪方法解决问题。我们知道最大差值在数组的最小和最大元素之间。利用这一事实,如果我们在答案中包括最小元素之一,则答案数组中包含的下一个元素将是最大元素,然后,包含的第三个元素将是第二个最小值,然后包含的第四个元素将是最大元素。第二个最大值,依此类推,将得到所需的数组。
步骤如下:

  1. 按给定数组arr []的升序排序。
  2. 从排序后的数组中选择第一个最大值(例如a )和最小值(例如b ),并以{a,b}的形式插入答案数组(例如ans [] )。
  3. 通过从排序数组中选择第二,第三,第四…个最大和最小元素来重复上述步骤,并将其插入答案数组的前面。
  4. 完成上述所有操作后,答案数组将具有所需的结果。

下面是上述方法的实现:

CPP
// C++ implementation of the above approach
  
#include 
using namespace std;
  
// Function that arrange the array such that
// all absolute difference between adjacent
// element are sorted
void sortedAdjacentDifferences(int arr[], int n)
{
    // To store the resultant array
    int ans[n];
  
    // Sorting the given array
    // in ascending order
    sort(arr + 0, arr + n);
  
    // Variable to represent left and right
    // ends of the given array
    int l = 0, r = n - 1;
  
    // Traversing the answer array in reverse
    // order and arrange the array elements from
    // arr[] in reverse order
    for (int i = n - 1; i >= 0; i--) {
  
        // Inserting elements in zig-zag manner
        if (i % 2) {
            ans[i] = arr[l];
            l++;
        }
        else {
            ans[i] = arr[r];
            r--;
        }
    }
  
    // Displaying the resultant array
    for (int i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
}
  
// Driver Code
int main()
{
    int arr[] = { 5, -2, 4, 8, 6, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    sortedAdjacentDifferences(arr, n);
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
  
class GFG{
   
// Function that arrange the array such that
// all absolute difference between adjacent
// element are sorted
static void sortedAdjacentDifferences(int arr[], int n)
{
    // To store the resultant array
    int []ans = new int[n];
   
    // Sorting the given array
    // in ascending order
    Arrays.sort(arr);
   
    // Variable to represent left and right
    // ends of the given array
    int l = 0, r = n - 1;
   
    // Traversing the answer array in reverse
    // order and arrange the array elements from
    // arr[] in reverse order
    for (int i = n - 1; i >= 0; i--) {
   
        // Inserting elements in zig-zag manner
        if (i % 2 == 1) {
            ans[i] = arr[l];
            l++;
        }
        else {
            ans[i] = arr[r];
            r--;
        }
    }
   
    // Displaying the resultant array
    for (int i = 0; i < n; i++) {
        System.out.print(ans[i]+ " ");
    }
}
   
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, -2, 4, 8, 6, 4, 5 };
    int n = arr.length;
   
    // Function Call
    sortedAdjacentDifferences(arr, n);
}
}
  
// This code is contributed by Princi Singh


Python3
# Python3 implementation of the above approach
  
# Function that arrange the array such that
# all absolute difference between adjacent
# element are sorted
def sortedAdjacentDifferences(arr, n):
      
    # To store the resultant array
    ans = [0]*n
  
    # Sorting the given array
    # in ascending order
    arr = sorted(arr)
  
    # Variable to represent left and right
    # ends of the given array
    l = 0
    r = n - 1
  
    # Traversing the answer array in reverse
    # order and arrange the array elements from
    # arr[] in reverse order
    for i in range(n - 1, -1, -1):
  
        # Inserting elements in zig-zag manner
        if (i % 2):
            ans[i] = arr[l]
            l += 1
        else:
            ans[i] = arr[r]
            r -= 1
  
    # Displaying the resultant array
    for i in range(n):
        print(ans[i], end=" ")
  
# Driver Code
if __name__ == '__main__':
    arr=[5, -2, 4, 8, 6, 4, 5]
    n = len(arr)
  
    # Function Call
    sortedAdjacentDifferences(arr, n)
      
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach
using System;
  
class GFG
{
    // Function that arrange the array such that
    // all absolute difference between adjacent
    // element are sorted
    static void sortedAdjacentDifferences(int[] arr, int n)
    {
        // To store the resultant array
        int[] ans = new int[n];
       
        // Sorting the given array
        // in ascending order
        Array.Sort(arr);
       
        // Variable to represent left and right
        // ends of the given array
        int l = 0, r = n - 1;
       
        // Traversing the answer array in reverse
        // order and arrange the array elements from
        // arr[] in reverse order
        for (int i = n - 1; i >= 0; i--) {
       
            // Inserting elements in zig-zag manner
            if (i % 2 != 0) {
                ans[i] = arr[l];
                l++;
            }
            else {
                ans[i] = arr[r];
                r--;
            }
        }
       
        // Displaying the resultant array
        for (int i = 0; i < n; i++) {
            Console.Write(ans[i] + " ");
        }
    }
       
    // Driver Code
    public static void Main()
    {
        int[] arr = { 5, -2, 4, 8, 6, 4, 5 };
        int n = arr.Length;
       
        // Function Call
        sortedAdjacentDifferences(arr, n);
    }
}
  
// This code is contributed by chitranayal


输出:
5 4 5 4 6 -2 8

时间复杂度: O(N * log N),其中N是给定数组中元素的数量。

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。