Arrange Elements From Center in an Array

Write a program in Java to accept a set of N integers where N > 0 in a single dimensional array.

Arrange the elements of the array such that the lowest number appears at the center of the array, next lower number in the right cell of the center, next lower in the left cell of the center and so on.

The process will stop when the highest number will be placed in its appropriate cell.

Finally, display the array elements.

Example:
INPUT:
N = 5
Elements: 1, 2, 3, 4, 5
OUTPUT:
5, 3, 1, 2, 4

import java.io.*;
class Arrange{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        int a[] = new int[n];
        System.out.println("Enter integers:");
        for(int i = 0; i < a.length; i++)
            a[i] = Integer.parseInt(br.readLine());
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length - 1 - i; j++){
                if(a[j] > a[j + 1]){
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        int b[] = new int[n];
        int mid = (a.length - 1) / 2;
        b[mid] = a[0];
        int left = mid - 1;
        int right = mid + 1;
        for(int i = 1; i < a.length; i++){
            if(i % 2 == 0)
                if(left >= 0)
                    b[left--] = a[i];
                else
                    b[right++] = a[i];
            if(i % 2 == 1)
                if(right < b.length)
                    b[right++] = a[i];
                else
                    b[left--] = a[i];
        }
        System.out.println("Required arrangement:");
        for(int i = 0; i < a.length; i++)
            System.out.print(b[i] + "\t");
        System.out.println();
    }
}
%d bloggers like this: