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]
1 Answer 1
Performance
You know exactly how long the resulting array should be, so don't make the interpreter guess. Any time the interpreter underestimates the length of an array and has to expand it, there's a significant performance penalty, as it reallocates a larger chunk of contiguous memory and transfers the already copied elements there.
var copyarray = new Array(arr.length);
That said, do you really need to copy the array? If not, then you should just swap the first k
elements in place for best performance.
As for the looping, it doesn't much matter whether you write it as one loop or two loops. The running time will be dominated by the memory accesses: n reads and n writes.
Code hygiene
Did you really drop a vowel from the function name to save one byte? If so, you are repeating Ken Thompson's greatest regret.
Although JavaScript allows you to omit semicolons at the end of each statement, it's considered bad practice to do so in all but the most trivial cases, such as <a onclick="alert('Hello')">Hello</a>
.
It's odd to have a function that just logs its results. Either return copyarray
(and let the caller call console.log()
), or reverse the entries in place.
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\$