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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
* PURPOSE: Takes in an integer array (arr[]), its length (N), and the number of elements to right-shift (M):
* PARAMETERS:
* arr[] , integer array
* N , its length
* M , number of elements to right shift
* RETURN VALUES:
* the new array after right shifting the elements.
*/
void rightShiftElementsbyOne(int arr[], int N);
/*Function to right rotate arr[] of size N by M elements*/
void rightShiftElements(int arr[], int N, int M)
{
int i;
for (i = 0; i < N - M; i++)
rightShiftElementsbyOne(arr, N);
}
void rightShiftElementsbyOne(int arr[], int N)
{
int i, temp;
temp = arr[0];
for (i = 0; i < N-1; i++)
arr[i] = arr[i+1];
arr[i] = temp;
}
/* utility function to print an array */
void printArray(int arr[], int size)
{
int i;
for(i = 0; i < size; i++)
printf("%d ", arr[i]);
}
/* Driver program to test above functions */
int main()
{
// it shifts to the right if (N - 2)+ M
int arr[] = {1, 2, 3, 4, 5, 6, 7};
rightShiftElements(arr, 7, 6);
printArray(arr, 7);
getchar();
return 0;
}
|