给定长度为N的未排序数组。任务是对数组进行排序,以使abs(a [i] -a [i + 1])<= abs(a [i + 1] -a [i + 2])对于所有0 <= i
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的位置,以使该数组的所有元素都在堆栈中。然后遍历整个堆栈,直到堆栈不为空,然后从堆栈中弹出元素并将其打印出来。
下面是讨论的方法的实现:
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
输出:
9 7 9 4 9 -1