📌  相关文章
📜  对数组进行排序,使相邻元素的绝对差按递增顺序排列

📅  最后修改于: 2021-09-08 12:37:55             🧑  作者: Mango

给定一个长度为 N 的未排序数组。任务是对数组进行排序,使得abs(a[i]-a[i+1]) < = abs(a[i+1]-a[i+2])对于所有 0 < = i< N 即 abs(a[0]-a[1]) < = abs(a[1]-a[2]) < = abs(a[2]-a[3])等等。
例子:

Input:  arr[] = {7, 4, 9, 9, -1, 9}
Output:  {9, 7, 9, 4, 9, -1}
Explanation:
For first two elements the difference is abs(9-7)=2
For next two elements the difference is abs(7-9)=2
For next two elements the difference is abs(9-4)=5
For next two elements the difference is abs(7-4)=3
For next two elements the difference is abs(4-(-1))=5
Hence, difference array is 0, 0, 2, 3, 5.

Input: arr[] = {1, 4, 6, 7} 
Output: {6, 4, 7, 1} 
Explanation:
For first two elements the difference is abs(6-4)=2
For next two elements the difference is abs(4-7)=3
For next two elements the difference is abs(7-1)=6
Hence, difference array is 2, 3, 6.

方法:
为了解决上面提到的问题,我们按升序对给定的未排序数组进行排序。然后运行一个从 i = 1 到 i < n/2 的循环,并分别从前半部分和后半部分交替地将元素推入堆栈中,即推 a[i] 一次和一次 a[ni-1] 直到整个数组元素被推入堆栈。
该问题的主要观察是检查给定数组的长度是否为奇数,然后将索引 n/2 处的元素另外压入,以便将数组的所有元素放入堆栈中。然后遍历整个栈直到栈不为空,将元素弹出栈并打印结果。
以下是所讨论方法的实现:

C++
// C++ implementation to Sort a given
// unsorted array of length n
// according to the given condition
#include 
using namespace std;
 
// Function
void solve(int a[], int n)
{
 
    // sort the array in ascending order
    sort(a, a + n);
 
    // declare a stack data structure
    stack st;
 
    // run a loop from i=0 to i


Java
// Java implementation to Sort a given
// unsorted array of length n
// according to the given condition
import java.util.*;
class GFG{
 
// Function
static void solve(int a[], int n)
{
 
    // sort the array in ascending order
    Arrays.sort(a);
 
    // declare a stack data structure
    Stack st = new Stack();
 
    // run a loop from i=0 to i


Python3
# Python3 implementation to sort a
# given unsorted array of length n
# according to the given condition
 
# Function
def solve(a, n):
 
    # Sort the array in ascending
    # order
    a.sort()
     
    # Declare a list used as a
    # stack data structure
    st = []
 
    # Run a loop from i=0 to i


C#
// C# implementation to Sort a given
// unsorted array of length n
// according to the given condition
using System;
using System.Collections;
 
class GFG{
 
// Function
static void solve(int[] a, int n)
{
     
    // Sort the array in ascending order
    Array.Sort(a);
 
    // Declare a stack data structure
    Stack st = new Stack();
 
    // Run a loop from i=0 to i


Javascript


输出:
9 7 9 4 9 -1

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