用于以摆锤排列打印数组的程序。
按照摆锤排列来排列数组元素。
- 对给定数组进行排序,创建一个空数组来存储结果。
- 将第 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP