Categories

# 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{
System.out.print("N = ");
int a[] = new int[n];
System.out.println("Enter integers:");
for(int i = 0; i < a.length; i++)
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();
}
}``````

## 6 replies on “Arrange Elements From Center in an Array”

sayan ranasays:

Sir,in the above program if it is told not to use any 2nd array then how to do the program assuming that the array size is small?

Haven’t figured it out yet.

sayan ranasays:

Sir,in the above program if it is told not to use any 2nd array then how to do the program?

Let me think of a solution for that.

sayan ranasays:

WAP in Java to accept a word and check whether it is a Magic string or not.A ‘Magic Word’ is a word which has at any position two consecutive letters. This can be achieved by taking the ASCII values of the characters.
Eg:
Sample Input:ABDOMEN
Sample output:Magic String

sayan ranasays:

Sir,in the above program if it is told not to use any 2nd array then how to do the program assuming that the array size is small?

This site uses Akismet to reduce spam. Learn how your comment data is processed.