在摆摆之后排列数组的元素。
对给定的数组进行排序,创建一个空数组来存储结果。
将第0个元素存储在变量temp中。
将元素1的元素存储在排序数组中结果数组第(mid+1)个位置的下一个元素中,将下一个元素存储在第(mid-1)个位置的第一个元素中,将下一个元素存储在(mid+2)个元素的第一个中,依此类推上。
示例
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));
}
}
输出结果
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]