Rearrange array such that difference of adjacent elements is in descending order

Given an array a[] with n integers the task is to rearrange the elements of the array in such a way that the differences of the adjacent elements are in descending order.
Examples:Â
Â
Input : arr[] = {1, 2, 3, 4, 5, 6}
Output : 6 1 5 2 4 3
Explanation:
For first two elements the difference is abs(6-1)=5
For next two elements the difference is abs(1-5)=4
For next two elements the difference is abs(5-2)=3
For next two elements the difference is abs(2-4)=2
For next two elements the difference is abs(4-3)=1
Hence, difference array is 5, 4, 3, 2, 1.
Input : arr[] = {7, 10, 2, 4, 5}
Output : 10 2 7 4 5
Explanation:
For first two elements the difference is abs(10-2)=8
For next two elements the difference is abs(2-7)=5
For next two elements the difference is abs(7-4)=3
For next two elements the difference is abs(4-5)=1
Hence, difference array is 8, 5, 3, 1.
Â
Approach:
To solve the problem mentioned above we have to sort the array and then print the elements in the following order for the even-sized array :
Â
a[n], a[1], a[n-1], a[2] ….. a[(n/2)], [(n/2)+1]Â
And for odd-sized array, we have to print array elements in the following order:
Â
a[n], a[1], a[n-1], a[2] ….. a[(n/2)+1]
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation to Rearrange array// such that difference of adjacent// elements is in descending orderÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to print array in given ordervoid printArray(int* a, int n){    // Sort the array    sort(a, a + n);    int i = 0;    int j = n - 1;Â
    // Check elements till the middle index    while (i <= j) {        // check if length is odd        // print the middle index at last        if (i == j) {            cout << a[i] << " ";        }        // Print the remaining elements        // in the described order        else {            cout << a[j] << " ";            cout << a[i] << " ";        }        i = i + 1;        j = j - 1;    }    cout << endl;}Â
// Driver codeint main(){Â
    // array declaration    int arr1[] = { 1, 2, 3, 4, 5, 6 };Â
    // size of array    int n1 = sizeof(arr1) / sizeof(arr1[0]);Â
    printArray(arr1, n1);} |
Java
// Java implementation to Rearrange array// such that difference of adjacent// elements is in descending orderimport java.util.*;Â
class GFG {     // Function to print array in given orderstatic void printArray(int []a, int n){         // Sort the array    Arrays.sort(a);         int i = 0;    int j = n - 1;         // Check elements till the     // middle index    while (i <= j)    {                 // Check if length is odd print        // the middle index at last        if (i == j)        {            System.out.print(a[i] + " ");        }                 // Print the remaining elements        // in the described order        else        {            System.out.print(a[j] + " ");            System.out.print(a[i] + " ");        }        i = i + 1;        j = j - 1;    }    System.out.println();}     // Driver codepublic static void main (String[] args) {         // Array declaration    int arr1[] = { 1, 2, 3, 4, 5, 6 };         // Size of array    int n1 = arr1.length;         printArray(arr1, n1);}   }Â
// This code is contributed by AnkitRai01 |
Python3
# Python3 implementation to rearrange # array such that difference of adjacent # elements is in descending order Â
# Function to print array in given order def printArray(a, n):          # Sort the array     a.sort();         i = 0;     j = n - 1; Â
    # Check elements till the middle index     while (i <= j):                 # Check if length is odd print        # the middle index at last         if (i == j):            print(a[i], end = " ");                      # Print the remaining elements         # in the described order         else :            print(a[j], end = " ");            print(a[i], end = " ");                  i = i + 1;         j = j - 1; Â
    print();Â
# Driver code if __name__ == "__main__" : Â
    # Array declaration     arr1 = [ 1, 2, 3, 4, 5, 6 ]; Â
    # Size of array     n1 = len(arr1); Â
    printArray(arr1, n1); Â
# This code is contributed by AnkitRai01 |
C#
// C# implementation to rearrange array// such that difference of adjacent// elements is in descending orderusing System;Â
class GFG {         // Function to print array in given orderstatic void printArray(int []a, int n){             // Sort the array    Array.Sort(a);             int i = 0;    int j = n - 1;             // Check elements till the     // middle index    while (i <= j)    {                     // Check if length is odd print        // the middle index at last        if (i == j)        {            Console.Write(a[i] + " ");        }                     // Print the remaining elements        // in the described order        else        {            Console.Write(a[j] + " ");            Console.Write(a[i] + " ");        }        i = i + 1;        j = j - 1;    }    Console.WriteLine();}         // Driver codepublic static void Main (string[] args) {             // Array declaration    int []arr1 = { 1, 2, 3, 4, 5, 6 };             // Size of array    int n1 = arr1.Length;             printArray(arr1, n1);}    }Â
// This code is contributed by AnkitRai01 |
Javascript
<script>Â
      // JavaScript implementation to Rearrange array      // such that difference of adjacent      // elements is in descending orderÂ
      // Function to print array in given order      function printArray(a, n)       {        // Sort the array        a.sort(function (a, b) {          return a - b;        });        var i = 0;        var j = n - 1;Â
        // Check elements till the middle index        while (i <= j) {          // check if length is odd          // print the middle index at last          if (i == j) {            document.write(a[i] + "  ");          }          // Print the remaining elements          // in the described order          else {            document.write(a[j] + "  ");            document.write(a[i] + "  ");          }          i = i + 1;          j = j - 1;        }        document.write("<br>");      }Â
      // Driver code      // array declaration      var arr1 = [1, 2, 3, 4, 5, 6];Â
      // size of array      var n1 = arr1.length;      printArray(arr1, n1);              </script> |
6 1 5 2 4 3
Â
Time Complexity:Â O(N * logN) the inbuilt sort function takes N log N time to complete all operations, hence the overall time taken by the algorithm is N log N
Auxiliary Space: O(1) since no extra array is used so the space taken by the algorithm is constant
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



