Array Rotation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ArrayRotation {
    
 public static void main(String[] args) {
  int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
  ArrayRotation ar = new ArrayRotation();
  ar.rotateA(arr, 3);

 }

 void rotateA(int[] arr, int k) {
     
  int c=0;
  while(c < k) {
  for ( int i = 0; i < arr.length - 1; i++) {
   int j = i + 1;
     if ((arr[j] < arr[i] || arr[i] >= arr[i]))  {
     int temp = arr[i];
     arr[i] = arr[j];
     arr[j] = temp;  
     }
  }
    c++;
  }
   for (int m = 0; m < arr.length; m++) {
   System.out.print(arr[m]+" ");
    }
  }
}
//Output: 4 5 6 7 8 1 2 3 
//Output: 4 5 6 7 8 1 2 3

No comments:

Post a Comment