Wap to perform right/left rotations on the array

Home  >>  JavaScript Tutorials  >>  Wap to perform right/left rotations on the array

Wap to perform right/left rotations on the array

23
Sep,2017

0

<html>
<head>
<title>CA2 – Push,Pop,Shift,Unshift Functions</title>
</head>
<body>
<script>
var temp;
var n=prompt(“Enter the number of arrays: “);
var a=new Array();
for(i=0;i<n;i++)
{
a[i]=prompt(“Enter “+(i+1)+” value: “);
}

document.write(“Your Element are: <br> “+a);

<!–left rotation using simple loops—>
var r=prompt(“<br>Enter the number of rotations: “);
function func1()
{
for(j=0;j<r;j++)
{
for(i=0;i<n-1;i++)
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
document.write(“<br>After rotation: <br>”+a);
}
//func1();

<!–left rotation using Functions—>
function func2()
{
var n1;
for(i=0;i<r;i++)
{
n1=a.shift();
a.push(n1);
}
document.write(“<br>After Rotation: <br>”+a);
}

//func2();

<!–Right Rotation—>
function func3()
{
var n2;
for(i=0;i<r;i++)
{
n2=a.pop();
a.unshift(n2);
}
document.write(“<br>Right Shift: <br>”+a);
}

func3();
</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *