Fastest algorithm for circle shift N sized array for M position

后端 未结 24 3056
温柔的废话
温柔的废话 2020-11-28 05:33

What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4] shift M = 2 positions should be [1 4 3 4 5 2 3

24条回答
  •  没有蜡笔的小新
    2020-11-28 05:42

    circleArray has some errors and is not working in all cases!

    The loop must continue while i1 < i2 NOT i1 < last - 1.

    void Shift(int* _array, int _size, int _moves)
    {
        _moves = _size - _moves;
        int i2 = _moves;
             int i1 = -1;
             while(++i1 < i2)
        {
            int tmp = _array[i2];
            _array[i2] = _array[i1];
            _array[i1] = tmp;
            if(++i2 == _size) i2 = _moves;
        }
    }
    

提交回复
热议问题