Program to print an array in Pendulum Arrangement with constant space

Given an array arr[] of integers, the task is to arrange them in a way similar to the to-and-fro movement of a Pendulum without using any extra space.
Pendulum Arrangement

  • The minimum element out of the list of integers must come in the center position of the array.
  • The number in the ascending order next to the minimum, goes to the right, the next higher number goes to the left of minimum number and it continues.
  • As higher numbers are reached, one goes to one side in a to-and-fro manner similar to that of a Pendulum.


Examples: 

Input: arr[] = {2, 3, 5, 1, 4} 
Output: 5 3 1 2 4 
The minimum element is 1, so it is moved to the middle. 
The next higher element 2 is moved to the right of the 
middle element while the next higher element 3 is 
moved to the left of the middle element and 
this process is continued.
Input: arr[] = {11, 2, 4, 55, 6, 8} 
Output: 11 6 2 4 8 55 


Approach: An approach which uses an auxiliary array has been discussed in this article. Here’s an approach without using extra space: 

  1. Sort the given array.
  2. Move all the odd position element in the right side of the array.
  3. Reverse the element from 0 to (n-1)/2 position of the array.

For example, let arr[] = {2, 3, 5, 1, 4} 
Sorted array will be arr[] = {1, 2, 3, 4, 5}. 
After moving all odd index position elements to the right, 
arr[] = {1, 3, 5, 2, 4} (1 and 3 are the odd index positions) 
After reversing elements from 0 to (n – 1) / 2, 
arr[] = {5, 3, 1, 2, 4} which is the required array. 
 

Below is the implementation of the above approach: 
 

C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

// Function to print the Pendulum
// arrangement of the given array
void pendulumArrangement(int arr[], int n)
{
    // Sort the array
    sort(arr, arr + n);

    int odd, temp, in, pos;

    // pos stores the index of
    // the last element of the array
    pos = n - 1;

    // odd stores the last odd index in the array
    if (n % 2 == 0)
        odd = n - 1;
    else
        odd = n - 2;

    // Move all odd index positioned
    // elements to the right
    while (odd > 0) {
        temp = arr[odd];
        in = odd;

        // Shift the elements by one position
        // from odd to pos
        while (in != pos) {
            arr[in] = arr[in + 1];
            in++;
        }
        arr[in] = temp;
        odd = odd - 2;
        pos = pos - 1;
    }

    // Reverse the element from 0 to (n - 1) / 2
    int start = 0, end = (n - 1) / 2;

    for (; start < end; start++, end--) {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
    }

    // Printing the pendulum arrangement
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}

// Driver code
int main()
{
    int arr[] = { 11, 2, 4, 55, 6, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);

    pendulumArrangement(arr, n);

    return 0;
}
Java
// Java implementation of the approach
import java.util.Arrays;
import java.io.*;

class GFG {

    // Function to print the Pendulum
    // arrangement of the given array
    static void pendulumArrangement(int arr[], int n)
    {
        // Sort the array
        // sort(arr, arr + n);

        Arrays.sort(arr);

        int odd, temp, in, pos;

        // pos stores the index of
        // the last element of the array
        pos = n - 1;

        // odd stores the last odd index in the array
        if (n % 2 == 0)
            odd = n - 1;
        else
            odd = n - 2;

        // Move all odd index positioned
        // elements to the right
        while (odd > 0) {
            temp = arr[odd];
            in = odd;

            // Shift the elements by one position
            // from odd to pos
            while (in != pos) {
                arr[in] = arr[in + 1];
                in++;
            }
            arr[in] = temp;
            odd = odd - 2;
            pos = pos - 1;
        }

        // Reverse the element from 0 to (n - 1) / 2
        int start = 0, end = (n - 1) / 2;

        for (; start < end; start++, end--) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        }

        // Printing the pendulum arrangement
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }

    // Driver code
    public static void main(String[] args)
    {

        int arr[] = { 11, 2, 4, 55, 6, 8 };
        int n = arr.length;

        pendulumArrangement(arr, n);
    }
}

// This code is contributed by akt_mit
Python
# Python 3 implementation of the approach

# Function to print the Pendulum
# arrangement of the given array
def pendulumArrangement(arr, n):
    
    # Sort the array
    arr.sort(reverse = False)

    # pos stores the index of
    # the last element of the array
    pos = n - 1

    # odd stores the last odd index in the array
    if (n % 2 == 0):
        odd = n - 1
    else:
        odd = n - 2

    # Move all odd index positioned
    # elements to the right
    while (odd > 0):
        temp = arr[odd]
        in1 = odd

        # Shift the elements by one position
        # from odd to pos
        while (in1 != pos):
            arr[in1] = arr[in1 + 1]
            in1 += 1

        arr[in1] = temp
        odd = odd - 2
        pos = pos - 1

    # Reverse the element from 0 to (n - 1) / 2
    start = 0
    end = int((n - 1) / 2)

    while(start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end -= 1

    # Printing the pendulum arrangement
    for i in range(n):
        print(arr[i], end = " ")

# Driver code
if __name__ == '__main__':
    arr = [11, 2, 4, 55, 6, 8]
    n = len(arr)

    pendulumArrangement(arr, n)

# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System; 

class GFG 
{

    // Function to print the Pendulum
    // arrangement of the given array
    static void pendulumArrangement(int[] arr, int n)
    {
        // Sort the array
        // sort(arr, arr + n);

        Array.Sort(arr);

        int odd, temp, p, pos;

        // pos stores the index of
        // the last element of the array
        pos = n - 1;

        // odd stores the last odd index in the array
        if (n % 2 == 0)
            odd = n - 1;
        else
            odd = n - 2;

        // Move all odd index positioned
        // elements to the right
        while (odd > 0) 
        {
            temp = arr[odd];
            p = odd;

            // Shift the elements by one position
            // from odd to pos
            while (p != pos)
            {
                arr[p] = arr[p + 1];
                p++;
            }
            arr[p] = temp;
            odd = odd - 2;
            pos = pos - 1;
        }

        // Reverse the element from 0 to (n - 1) / 2
        int start = 0, end = (n - 1) / 2;

        for (; start < end; start++, end--) 
        {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        }

        // Printing the pendulum arrangement
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }

    // Driver code
    public static void Main()
    {

        int[] arr = { 11, 2, 4, 55, 6, 8 };
        int n = arr.Length;

        pendulumArrangement(arr, n);
    }
}

// This code is contributed by ChitraNayal
Javascript
<script>
    // Javascript implementation of the approach
    
    // Function to print the Pendulum
    // arrangement of the given array
    function pendulumArrangement(arr, n)
    {
        // Sort the array
        // sort(arr, arr + n);
  
        arr.sort(function(a, b){return a - b});
  
        let odd, temp, p, pos;
  
        // pos stores the index of
        // the last element of the array
        pos = n - 1;
  
        // odd stores the last odd index in the array
        if (n % 2 == 0)
            odd = n - 1;
        else
            odd = n - 2;
  
        // Move all odd index positioned
        // elements to the right
        while (odd > 0) 
        {
            temp = arr[odd];
            p = odd;
  
            // Shift the elements by one position
            // from odd to pos
            while (p != pos)
            {
                arr[p] = arr[p + 1];
                p++;
            }
            arr[p] = temp;
            odd = odd - 2;
            pos = pos - 1;
        }
  
        // Reverse the element from 0 to (n - 1) / 2
        let start = 0, end = parseInt((n - 1) / 2, 10);
  
        for (; start < end; start++, end--) 
        {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        }
  
        // Printing the pendulum arrangement
        for (let i = 0; i < n; i++)
            document.write(arr[i] + " ");
    }
    
    let arr = [ 11, 2, 4, 55, 6, 8 ];
    let n = arr.length;

    pendulumArrangement(arr, n);
    
</script>
PHP
<?php
// PHP implementation of the approach 

// Function to print the Pendulum 
// arrangement of the given array 
function pendulumArrangement($arr, $n) 
{ 
    // Sort the array 
    sort($arr) ; 

    // pos stores the index of 
    // the last element of the array 
    $pos = $n - 1; 

    // odd stores the last odd index in the array 
    if ($n % 2 == 0) 
        $odd = $n - 1; 
    else
        $odd = $n - 2; 

    // Move all odd index positioned 
    // elements to the right 
    while ($odd > 0)
    { 
        $temp = $arr[$odd]; 
        $in = $odd; 

        // Shift the elements by one position 
        // from odd to pos 
        while ($in != $pos) 
        { 
            $arr[$in] = $arr[$in + 1]; 
            $in++; 
        } 
        $arr[$in] = $temp; 
        $odd = $odd - 2; 
        $pos = $pos - 1; 
    } 

    // Reverse the element from 0 to (n - 1) / 2 
    $start = 0;
    $end = floor(($n - 1) / 2); 

    for (; $start < $end; $start++, $end--) 
    { 
        $temp = $arr[$start]; 
        $arr[$start] = $arr[$end]; 
        $arr[$end] = $temp; 
    } 

    // Printing the pendulum arrangement 
    for ($i = 0; $i < $n; $i++) 
        echo $arr[$i], " "; 
} 

// Driver code 
$arr = array( 11, 2, 4, 55, 6, 8 ); 
$n = count($arr); 

pendulumArrangement($arr, $n); 

// This code is contributed by AnkitRai01

?>

Output
11 6 2 4 8 55 

Time Complexity: O(n2)
Auxiliary Space: O(1)

Approach: Optimized In-Place Pendulum Arrangement

To achieve an in-place pendulum arrangement of an array, we’ll refine the sorting and repositioning process without unnecessary moves. The key idea is to sort the array first, then directly rearrange the elements by simulating the placement of each element at its correct pendulum position without additional shifting.

Steps of the Algorithm:

  • Sort the Array:
    • First, sort the array in ascending order.
  • Pendulum Reordering:
    • Calculate and store target indices directly derived from the pendulum pattern.
    • Swap elements directly into their target positions in a controlled manner to prevent overwriting.
C++
#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int> pendulumArrangement(std::vector<int> arr)
{
    int n = arr.size();
    std::sort(arr.begin(), arr.end());

    // Resultant array with pendulum arrangement
    // Start by placing the smallest element at the middle
    std::vector<int> result(n);
    int mid = (n - 1) / 2;

    // Place elements in the pendulum arrangement
    int left = mid, right = mid + 1;
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            result[left--] = arr[i];
        }
        else {
            result[right++] = arr[i];
        }
    }

    return result;
}

int main()
{
    std::vector<int> arr = { 11, 2, 4, 55, 6, 8 };
    std::vector<int> result = pendulumArrangement(arr);
    for (int num : result) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
Java
import java.util.Arrays;

public class PendulumArrangement {
    public static int[] pendulumArrangement(int[] arr)
    {
        int n = arr.length;
        Arrays.sort(arr);

        // Resultant array with pendulum arrangement
        // Start by placing the smallest element at the
        // middle
        int[] result = new int[n];
        int mid = (n - 1) / 2;

        // Place elements in the pendulum arrangement
        int left = mid, right = mid + 1;
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                result[left--] = arr[i];
            }
            else {
                result[right++] = arr[i];
            }
        }

        // Place the sorted array back into the original
        // with the correct ordering
        for (int i = 0; i < n; i++) {
            arr[i] = result[i];
        }

        return arr;
    }

    public static void main(String[] args)
    {
        int[] arr = { 11, 2, 4, 55, 6, 8 };
        System.out.println(
            Arrays.toString(pendulumArrangement(arr)));
    }
}

// This code is contributed by Shivam
Python
def pendulumArrangement(arr):
    n = len(arr)
    arr.sort()

    # Resultant array with pendulum arrangement
    # Start by placing the smallest element at the middle
    result = [0] * n
    mid = (n - 1) // 2

    # Place elements in the pendulum arrangement
    left, right = mid, mid + 1
    for i, value in enumerate(arr):
        if i % 2 == 0:
            result[left] = value
            left -= 1
        else:
            result[right] = value
            right += 1

    # Place the sorted array back into the original with the correct ordering
    for i in range(n):
        arr[i] = result[i]

    return arr


# Example usage
arr = [11, 2, 4, 55, 6, 8]
print(pendulumArrangement(arr))  # Output: [11, 6, 2, 4, 8, 55]
JavaScript
function pendulumArrangement(arr) {
    const n = arr.length;
    arr.sort((a, b) => a - b);

    // Resultant array with pendulum arrangement
    // Start by placing the smallest element at the
    // middle
    const result = new Array(n);
    const mid = Math.floor((n - 1) / 2);

    // Place elements in the pendulum arrangement
    let left = mid, right = mid + 1;
    for (let i = 0; i < n; i++) {
        if (i % 2 === 0) {
            result[left--] = arr[i];
        } else {
            result[right++] = arr[i];
        }
    }

    // Convert result array to original array
    for (let i = 0; i < n; i++) {
        arr[i] = result[i];
    }

    return arr;
}

const arr = [11, 2, 4, 55, 6, 8];
console.log(pendulumArrangement(arr));

Output
[11, 6, 2, 4, 8, 55]

Time Complexity: O(NlogN) due to the sorting step. The rearrangement itself is O(N), making the sort the dominant factor.

Auxiliary Space: O(n). The solution uses an additional space proportional to the input size.



Contact Us