Java 程式迴圈旋轉陣列一次。


迴圈旋轉陣列的內容 −

  • 建立一個空變數。(temp)
  • 將陣列的最後一個元素儲存在其中。
  • 現在,從陣列的第 n 個元素開始,用前一個元素替換當前元素。
  • 將 temp 中的元素儲存在第 1 個位置。

示例

 即時演示

import java.util.Arrays;
import java.util.Scanner;
public class CyclicallyRotateanArray {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the required size of the array ::");
      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();
      }
      System.out.println("Contents of the array: "+Arrays.toString(myArray));
      int temp = myArray[size-1];
      for(int i = size-1; i>0; i--){
         myArray[i] = myArray[i-1];
      }
      myArray[0] = temp;
      System.out.println("Contents of the cycled array: "+Arrays.toString(myArray));
   }
}

輸出

Enter the required size of the array ::
5
Enter elements of the array
14
15
16
17
18
Contents of the array: [14, 15, 16, 17, 18]
Contents of the cycled array: [18, 14, 15, 16, 17]

更新時間: 2019 年 7 月 30 日

3K+ 檢視次數

開啟您的 職業生涯

完成該課程獲得認證

開始
廣告
© . All rights reserved.