Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

Rotate Array elements (clockwise) without using fft / ifft /circshift/cconv or any other built in function in MATLAB

Rotate Array

Given an unsorted array  , rotate it by D elements (clockwise). 
[You are not allowed to use any built in function]

Sample input & output:

1 2 3 4 5  when rotated by 2 elements, it becomes 3 4 5 1 2.


MATLAB CODE:

x=input('Enter the array:');
Y=[];
a=input('Enter the required amount of circular shift:');
k=1;
for i=a+1:length(x)
    Y(k)=x(i);
    k=k+1;
end
for i=1:a
    Y(k)=x(i);
    k=k+1;
end
disp(Y)


Output:


Explanation:



JAVA CODE:

import java.util.Scanner;
class Shi
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the array length:");
int n=obj.nextInt();
int x[]=new int[n];
int y[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the numbers in the array:");
x[i]=obj.nextInt();
}
System.out.println("Enter the required amount of shift:");
int d=obj.nextInt();
int k=0;
for (int i=d;i<=x.length-1;i++)
{
y[k]=x[i];
k=k+1;
}
for(int i=0;i<d;i++)
{
y[k]=x[i];
k++;
}
System.out.println("The rotated array is:");
for(int i=0;i<n;i++)
{
System.out.print(y[i]+" ");
}
}
}




No comments

Popular Posts