import java.io.*; class Pendulum_Array { public static void main(String args[]) throws IOException { BufferedReader br= new BufferedReader( new InputStreamReader(System.in)); System.out.print( "nEnter number of elements: " ); // Inputting the number of elements int n = Integer.parseInt(br.readLine()); int A[]= new int [n]; //original array int B[]= new int [n]; //array for storing the result /*Inputting the Array*/ for ( int i= 0 ; i<n; i++) { System.out.print( "Enter Element " +(i+ 1 )+ ": " ); A[i] = Integer.parseInt(br.readLine()); } /*Sorting the Inputted Array in Descending Order*/ int t= 0 ; for ( int i= 0 ; i<n- 1 ; i++) { for ( int j=i+ 1 ; j<n; j++) { if (A[i]<A[j]) // Note: We have changed the sign to '<' here { t=A[i]; A[i]=A[j]; A[j]=t; } } } /*Printing the Sorted Array*/ System.out.println( "\nThe Sorted Array Is" ); for ( int i= 0 ; i<n; i++) { System.out.print(A[i]+ "\t" ); } int mid = (n- 1 )/ 2 ; //finding index of middle cell int x = 1 , lim = n- 1 -mid; /*'x' is for accessing elements of array A[] and 'lim' is for the number of times we have to make this to-and-fro movement*/ /* Pendulum Arrangement Starts Here */ B[mid]=A[ 0 ]; //putting the maximum element in the middle cell for ( int i= 1 ; i<=lim; i++) { /* Note: Below we are first going to the left side then to the right, just the opposite of the above code */ if ((mid-i)>= 0 ) B[mid-i]=A[x++]; if ((mid+i)<n) B[mid+i]=A[x++]; } /*Printing the Result*/ System.out.println( "\n\nThe Result Is" ); for ( int i= 0 ; i<n; i++) { System.out.print(B[i]+ "\t" ); } } } |
Output:
Example 1:
Enter number of elements: 5
Enter Element 1: 1
Enter Element 2: 2
Enter Element 3: 3
Enter Element 4: 4
Enter Element 5: 5
Enter number of elements: 5
Enter Element 1: 1
Enter Element 2: 2
Enter Element 3: 3
Enter Element 4: 4
Enter Element 5: 5
The Sorted Array Is
5 4 3 2 1
5 4 3 2 1
The Result Is
2 4 5 3 1
2 4 5 3 1