7. Cyclically rotate an array by one.

7. Cyclically rotate an array by one.


Problem link :- click here
This problem is too easy.


C code

//Rotate
#include<stdio.h>

void rotate(int A[], int n)
{
    int x, i;
    x = A[n-1];
    for(i=n-1; i>=0; i--)
        A[i] = A[i-1];
    A[0] = x;
}

void main()
{
    int arr[30];
    int n, i;

    printf("Enter the size of the array\n");
    scanf("%d",&n);
    printf("Enter the elements of the array\n");
    for(i=0; i<n; i++)
        scanf("%d",&arr[i]);

    printf("Given Array\n");
    for(i=0; i<n; i++)
        printf("\t%d",arr[i]);
    printf("\n");

    rotate(arr, n);

    printf("\n\nArray after rotation\n");
    for(i=0; i<n; i++)
        printf("\t%d",arr[i]);
    printf("\n\n");
}

Java code

//Rotate cyclically by 1
package programs;

import java.util.*;

public class Array__7
{

	static void rotate(int arr[], int n)
	{
		int i, last;
		last = arr[n-1];
		for(i=n-1; i>0; i--)
		{
			arr[i] = arr[i-1];
		}
		arr[0] = last;
	}
	
	public static void main(String[] args)
	{
		int array[] = new int[20];
		int n, i;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the size of the array :");
		n = s.nextInt();
		System.out.println("Enter the elements of the array :");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		System.out.println("Given Array :");
		print_array(array, n);
		System.out.println("\n\n");
		
		rotate(array, n);
		System.out.println("Array after rotating :");
		print_array(array, n);

	}

	static void print_array(int arr[], int n)
	{
		for(int i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)


Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree