Fastest algorithm for circle shift N sized array for M position

后端 未结 24 3044
温柔的废话
温柔的废话 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 06:00

    C arrayShiftRight function. If shift is negative the function shifts array left. It is optimized for less memory usage. Running time is O(n).

    void arrayShiftRight(int array[], int size, int shift) {
        int len;
    
        //cut extra shift
        shift %= size;
    
        //if shift is less then 0 - redirect shifting left
        if ( shift < 0 ) {
            shift += size;
        }
    
        len = size - shift;
    
        //choosing the algorithm which needs less memory
        if ( shift < len ) {
            //creating temporary array
            int tmpArray[shift];
    
            //filling tmp array
            for ( int i = 0, j = len; i < shift; i++, j++ ) {
                tmpArray[i] = array[j];
            }
    
            //shifting array
            for ( int i = size - 1, j = i - shift; j >= 0; i--, j-- ) {
                array[i] = array[j];
            }
    
            //inserting lost values from tmp array
            for ( int i = 0; i < shift; i++ ) {
                array[i] = tmpArray[i];
            }
        } else {
            //creating temporary array
            int tmpArray[len];
    
            //filling tmp array
            for ( int i = 0; i < len; i++ ) {
                tmpArray[i] = array[i];
            }
    
            //shifting array
            for ( int i = 0, j = len; j < size; i++, j++ ) {
                array[i] = array[j];
            }
    
            //inserting lost values from tmp array
            for ( int i = shift, j = 0; i < size; i++, j++ ) {
                array[i] = tmpArray[j];
            }
        }
    }
    

提交回复
热议问题