简体   繁体   中英

In c++ take an integer array (arr[]), its length (N), and the number of elements to right-shift (M):?

How can I finish my code to take an integer array (arr[]), its length (N), and the number of elements to right-shift (M).

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void shiftright (int myarray[], int size);

int main (void)
{
    int myarray [] = {1, 2, 3, 4, 5};
    shiftright( myarray, 5);

    for ( int i = 0; i < 5; i++)
    {
        cout << myarray[i] << ' ';
    }

    return (0);
}

void shiftright (int myarray[], int size, int M)
{
    for (int m = (size - 1); m >= 1; m--) {
        int temp = myarray[size - 1];

        for (int i = (size - 1); i >= 1; i--)
        {
            myarray[i] = myarray[i - 1] ;
        }
        myarray[0] = temp;
    }
}

Instead of rolling your own, simply use a standard algorithm.

  if (m > 0 && size > 0)
      std::rotate(myarray, myarray + m % size, myarray + size);

Looks like you're trying to perform a "rotate" operation. Have you considered creating an indexer with an offset and not actually having to rotate anything at all? (This is far less costly.)

Anyways, just remove your outer loop to shift once:

void shiftright (int myarray[], int size)
{
    int temp = myarray[size - 1];

    for (int i = (size - 1); i >= 1; i--)
    {
        myarray[i] = myarray[i - 1];
    }

    myarray[0] = temp;
}

Now, you may create another method to shift m times:

void shiftright (int myarray[], int size, int m)
{
    for (int i = 0; i < m; i++)
    {
        shiftright(myarray, size);
    }
}

This is obviously very costly in terms of performance, so you may want to explain what you need this for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM