In: Computer Science
// Java program to create and test rearrange method
public class Rearrange {
// method to rearrange the array elements
public static void rearrange(int array[])
{
int temp[] = new int[array.length]; // create a temporary array of same length as input array
int i=0, j=0; // set i and j to start index
// loop that continues till we reach middle of the array
while(i<array.length/2)
{
temp[j] = array[i]; // set ith element of array to jth element of temp
j++; // increment j
temp[j] = array[array.length-1-i]; // set ith element from last of array to jth element of temp
j++; // increment j
i++; // increment i
}
// if array contains odd elements , copy the middle element of array to temp
if(array.length%2 != 0)
{
temp[j] = array[array.length/2];
}
// copy the element from temp back to array
for(i=0;i<array.length;i++)
{
array[i] = temp[i];
}
}
public static void main(String[] args) {
// test the method
int arr[] = {5,7,13,4,9};
int arr1[] = {5,7,13,4,9,10};
System.out.println("Before : "+Arrays.toString(arr));
rearrange(arr);
System.out.println("After rearrange : "+Arrays.toString(arr));
System.out.println("Before : "+Arrays.toString(arr1));
rearrange(arr1);
System.out.println("After rearrange : "+Arrays.toString(arr1));
}
}
//end of program
Output: