K
K
kate2018-11-08 22:57:12
C++ / C#
kate, 2018-11-08 22:57:12

How to write a function to rotate an array?

Implement a function with an array of type int that rotates the array a given number of positions to the left. If a negative shift is given, the function throws an exception.
What parameters to pass to the function if I read the array itself and the shift number from the main function?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2018-11-08
@Rsa97

Array address, array size, shift

V
Vitaly, 2018-11-08
@vt4a2h

Implement a function of type int,

Does this mean the function should return an int? If yes, then why?
So pass these parameters.
You can also do it the way std::rotate is implemented. But it's a little more difficult for beginners.

R
res2001, 2018-11-09
@res2001

An in-place array rotation algorithm is described in John Bentley's Programming Gem 2nd Edition, Addison-Wesley, Peter, 2002, Chapter 2, Section 2.3.
Here is an implementation example. In the same place I saw a more decent implementation of the same algorithm (in terms of code design), but I can’t find it right away.
The shift algorithm is not "in place" (with memory allocation for the result array) is simple, it is implemented by two memory copy operations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question