Fastest algorithm for circle shift N sized array for M position

后端 未结 24 3041
温柔的废话
温柔的废话 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:57

    Here is a nother one (C++):

    void shift_vec(vector& v, size_t a)
    {
        size_t max_s = v.size() / a;
        for( size_t s = 1; s < max_s; ++s )
            for( size_t i = 0; i < a; ++i )
                swap( v[i], v[s*a+i] );
        for( size_t i = 0; i < a; ++i )
            swap( v[i], v[(max_s*a+i) % v.size()] );
    }
    

    Of course it is not nearly as elegant as the famous reverse-three-times solution, but depending on the machine it can be similary fast.

提交回复
热议问题