jayati

Rotate Array

Jan 8th, 2024
909
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7. class Solution{
  8.     public:
  9.    
  10.     void reverse(int arr[], int low, int high){
  11.         while(low<high){
  12.             swap(arr[low], arr[high]);
  13.             low++;
  14.             high--;
  15.         }
  16.     }
  17.     //Function to rotate an array by d elements in counter-clockwise direction.
  18.     void rotateArr(int arr[], int d, int n){
  19.         // code here
  20.         d = d%n;
  21.         reverse(arr, 0, d-1);
  22.         reverse(arr, d, n-1);
  23.         reverse(arr, 0, n-1);
  24.     }
  25. };
  26.  
  27. //{ Driver Code Starts.
  28.  
  29. int main() {
  30.     int t;
  31.     //taking testcases
  32.     cin >> t;
  33.    
  34.     while(t--){
  35.         int n, d;
  36.        
  37.         //input n and d
  38.         cin >> n >> d;
  39.        
  40.         int arr[n];
  41.        
  42.         //inserting elements in the array
  43.         for(int i = 0; i < n; i++){
  44.             cin >> arr[i];
  45.         }
  46.         Solution ob;
  47.         //calling rotateArr() function
  48.         ob.rotateArr(arr, d,n);
  49.        
  50.         //printing the elements of the array
  51.         for(int i =0;i<n;i++){
  52.             cout << arr[i] << " ";
  53.         }
  54.         cout << endl;
  55.     }
  56.     return 0;
  57. }
  58. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment