Sort array such that absolute difference of adjacent elements is in increasing order

Given an unsorted array of length N. The task is to sort the array, such that abs(a[i]-a[i+1]) < = abs(a[i+1]-a[i+2]) for all 0 < = i< N that is abs(a[0]-a[1]) < = abs(a[1]-a[2]) < = abs(a[2]-a[3]) and so on.

Examples:

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.

Approach:

To solve the problem mentioned above we sort the given unsorted array in ascending order. Then run a loop from i = 1 to i < n/2 and push elements alternatively in a stack from first half and second half respectively, that is push a[i] once and a[n-i-1] once until the whole array elements get pushed into the stack.

The main observation of the problem is to check if the length of the given array is odd, then push element at index n/2 additionally in order to have all elements of the array in the stack. Then traverse the whole stack until the stack is not empty, and pop elements out of the stack and print them as a result.



Below is the implementation of the discussed approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to Sort a given
// unsorted array of length n
// according to the given condition
#include <bits/stdc++.h>
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<int> st;
  
    // run a loop from i=0 to i<n/2 and
    // push elements alternatively to stack
    for (int i = 0; i < n / 2; i++) {
  
        // push elements from
        // first half of array
        st.push(a[i]);
  
        // push elements from
        // second half of the array
        st.push(a[n - i - 1]);
    }
  
    // check if array has odd length,
    // then push a[n/2] to the stack
    if (n % 2 == 1)
  
        st.push(a[n / 2]);
  
    // loop until stack is not empty)
    while (!st.empty()) {
  
        int x = st.top();
  
        printf("%d ", x);
  
        // pop the topmost
        // element from the stack
        st.pop();
    }
}
  
// Driver code
int main()
{
  
    // declaration of unsorted array
    int a[] = { 7, 4, 9, 9, -1, 9 };
  
    // given size of unsorted array
    int n = sizeof(a) / sizeof(a[0]);
  
    solve(a, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<Integer> st = new Stack<Integer>();
  
    // run a loop from i=0 to i<n/2 and
    // push elements alternatively to stack
    for (int i = 0; i < n / 2; i++) 
    {
  
        // push elements from
        // first half of array
        st.add(a[i]);
  
        // push elements from
        // second half of the array
        st.add(a[n - i - 1]);
    }
  
    // check if array has odd length,
    // then push a[n/2] to the stack
    if (n % 2 == 1)
  
        st.add(a[n / 2]);
  
    // loop until stack is not empty)
    while (!st.isEmpty()) 
    {
        int x = st.peek();
        System.out.printf("%d ", x);
  
        // pop the topmost
        // element from the stack
        st.pop();
    }
}
  
// Driver code
public static void main(String[] args)
{
  
    // declaration of unsorted array
    int a[] = { 7, 4, 9, 9, -1, 9 };
  
    // given size of unsorted array
    int n = a.length;
  
    solve(a, n);
}
}
  
// This code is contributed by sapnasingh4991

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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<n/2 and
    # push elements alternatively to stack
    for i in range(n // 2):
  
        # Push elements from
        # first half of array
        st.append(a[i])
  
        # Push elements from
        # second half of the array
        st.append(a[n - i - 1])
  
    # Check if array has odd length,
    # then push a[n/2] to the stack
    if(n % 2 == 1):
  
        st.append(a[n // 2])
  
    # Loop until stack is not empty
    while(st != []):
        x = st[-1]
        print(x, end = " ")
  
        # Pop the topmost element 
        # from the stack
        st.pop()
  
# Driver code
if __name__ == '__main__':
  
    # Declaration of unsorted array
    a = [ 7, 4, 9, 9, -1, 9 ]
  
    # Given size of unsorted array 
    n = len(a)
  
    solve(a, n)
      
# This code is contributed by Shivam Singh

chevron_right


Output:

9 7 9 4 9 -1

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.