fork download
  1. //
  2. // main.cpp
  3. // Reversal Algorithm (Array rotation)
  4. //
  5. // Created by Himanshu on 18/09/21.
  6. //
  7.  
  8. #include <iostream>
  9.  
  10. using namespace std;
  11. const int N = 5;
  12.  
  13. void printArray (int A[]) {
  14. for (int i=0; i<N; i++) {
  15. cout<<A[i]<<" ";
  16. }
  17. cout<<endl;
  18. }
  19.  
  20. void Reverse (int A[], int p, int q) {
  21. int temp;
  22. for(int i=p, j=q; i<j; i++, j--) {
  23. temp = A[i];
  24. A[i] = A[j];
  25. A[j] = temp;
  26. }
  27. }
  28.  
  29. void Rotate (int A[], int d) {
  30. cout<<"Array:"<<endl;
  31. printArray(A);
  32.  
  33. Reverse(A, 0, d-1);
  34. Reverse(A, d, N-1);
  35. Reverse(A, 0, N-1);
  36.  
  37. }
  38.  
  39. int main() {
  40. int A[N] = {5, 2, 4, 6, 1};
  41. int d = 4;
  42.  
  43. Rotate(A, d);
  44.  
  45. cout<<"Array after "<<d<<" rotations:"<<endl;
  46. printArray(A);
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
Array:
5 2 4 6 1 
Array after 4 rotations:
1 5 2 4 6