用於以擺錘排列列印陣列的程式。


按照擺錘排列來排列陣列元素。

  • 對給定陣列進行排序,建立一個空陣列來儲存結果。
  • 將第 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]

更新於: 2019 年 7 月 30 日

648 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告