How to cyclically rotate the elements of int array left N times in Java

1 Answer

0 votes
public class MyClass {
    static void rotate_array_left_one_time(int[] arr) {
        int first = arr[0];
        int arr_size = arr.length;
   
        for (int i = 0; i < arr_size - 1; i++) {
            arr[i] = arr[i + 1];
        }
          
        arr[arr_size - 1] = first;
    }
    public static void main(String args[]) {
        int[] arr = new int[] { 4, 7, 2, 9, 3 };
        int arr_size = arr.length;
        int n_times = 3;
   
        for (int i = 0; i < n_times; i++)
            rotate_array_left_one_time(arr);
       
        for (int i = 0; i < arr_size; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}




/*
run:
   
9 3 4 7 2  
   
*/

 



answered Jul 31, 2021 by avibootz
...