Program for printing array in Pendulum Arrangement.


To arrange elements of the array following pendulum arrangement.

  • Sort the given array, create an empty array to store the result.
  • Store the 0th element in a variable say temp.
  • Store the element at index 1 in the sorted array in (mid+1)st position of the resultant array, and the next element int the (mid-1)st position and the next element in (mid+2)nd element and so on.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class ArrayinPendulumArrangement {
   public static int[] swap(int origPos, int newPos, int[] array){
      origPos = 1;
      newPos = 4;
      int temp = array[origPos];
      array[origPos] = array[newPos];
      array[newPos] = temp;
      System.out.println(Arrays.toString(array));
      return array;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the required size of the array (odd) :");
      int size = sc.nextInt();
      int [] myArray = new int[size];
      System.out.println("Enter elements of the array :");
      for(int i = 0; i< size; i++){
         myArray[i] = sc.nextInt();
      }
      //Sort the given array
      Arrays.sort(myArray);
      System.out.println("Contents of the Array"+Arrays.toString(myArray));
      int temp = myArray[0];
      int mid = (size-1)/2;
      int k =1;
      int[] result = new int[size];
      for(int i = 1; i<=mid; i++){
         result[mid+i] = myArray[k++];
         result[mid-i] = myArray[k++];
      }
      result[mid] = temp;
      System.out.println("Pendulum arrangement "+Arrays.toString(result));
   }
}

Output

Enter the required size of the array (odd) :
5
Enter elements of the array :
12
28
46
77
39
Contents of the Array[12, 28, 39, 46, 77]
Pendulum arrangement[77, 39, 12, 28, 46]

Updated on: 30-Jul-2019

543 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements