I have an array and I need to make one function which has two parameters, array
and K
. I need to return a new array with only K
elements reversed, the rest becoming the same as in array
. I am able to get correct results but I think its performance is too slow. Is there any better solution to get the same results?
var arry=[2,3,1,5,7,9];
var k=3
function reverseOnlyK_elment(arr,k){
var copyarray=[];
var j=0;
for(var i=k-1;i>=0;i--){
copyarray[j++]=arr[i]
}
for(var i=k;i<=arr.length-1;i++){
copyarray[j++]=arr[i]
}
console.log(copyarray)
}
reverseOnlyK_elment(arry,k)
Expected output:
[1, 3, 2, 5, 7, 9]
i=0
andj=k
and the condition isi < j
. Then in each iterationvar temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
. And after each iterationi++, j--
. \$\endgroup\$