Array loop shift operation instance

  • 2020-04-02 01:34:01
  • OfStack

Topic:
For example, the required time complexity is O(N).

Solution:
Move k bit to the right, the k bit in reverse order, the N-k bit in reverse order, and then the whole reverse order.

#include <stdio.h>   
#include <stdlib.h>   

void reverse(int* array, int b, int e)   
{   
    int temp = 0;   
    for(; b < e; b++,e--)   
    {   
        temp = array[e];   
        array[e] = array[b];   
        array[b] = temp;   
    }   
    return;   
}   

void rightShift(int* array, int n, int k)   
{   
    k = k % n;   
    reverse(array, 0, n - k - 1);   
    reverse(array, n - k, n - 1);   
    reverse(array, 0, n - 1);   
    return;   
}   

int main()   
{   
    int array[] = {6,7,8,9,1,2,3,4};   
    int i = 0;   
    rightShift(array, 8, 4);   
    for (; i < 8; i++)   
    {   
        printf("%dn", array[i]);   
    }   
    return 0;   
}

Related articles: