rotate an integer array

Given an integer array you have to rotate the array by n times (n< no of array elements)using only swap.

Comments

  1. You can do this in linear time by using a reverse() helper.

    // rotate array of size=size, by n positions
    void rotate(int array[], int size, int n)
    {
    // reverse array[0...size-1]
    reverse(array, 0, size-1);

    // reverse A[0...n-1]
    reverse(array, 0, n-1);

    // reverse A[n...size-1]
    reverse(array, n, size-1);
    }

    code :
    void rev(int arr[],int start,int last)
    {
    int i,temp,j;
    for(i=start,j=last;i<j;i++,j--)
    {
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    }

    }

    int main()
    {
    int arr[]={1,2,3,4,5},i;
    rev(arr,0,4);
    rev(arr,0,1);
    rev(arr,2,4);
    for(i=0;i<5;i++)
    printf("%d \t ",arr[i]);
    return 0;
    }

    this runs in linear time.

    ReplyDelete

Post a Comment

Popular posts from this blog