Why Is This Javascript Function Not Reversing The Array?
Solution 1:
You are reversing it twice. Replace array.length with array.length/2
functionreverseArrayInPlace(array){
var temp = 0;
for (var i =0; i < array.length/2; ++i){
temp = array[i];
array[i] = array[array.length - (i+1)];
array[array.length - ( i + 1 )] = temp;
}
}
Solution 2:
Arun's answer shows the proper code to do what you're looking for.
The answer to why your code isn't working as expected is because you're looping through the entire array, swapping every variable with its mirror image. Once you've gone past halfway, though, your line of code that is setting the mirror image:
array[array.length - ( i + 1 )]
is swapping the array back into the original order.
Add this line just after your temp = array[i];
line:
console.log('Swapping ' + array[i] + ' with ' + array[array.length - (i+1)]);
When you run your code now, you should immediately see why you need to stop at the halfway point.
You should see:
Swapping 10with6
Swapping 9with7
Swapping 8with8
Swapping 9with7
Swapping 10with6
Now, run with Arun's code and you'll see:
Swapping 10with6
Swapping 9with7
Swapping 8with8
[ 6, 7, 8, 9, 10 ]
Make sense?
Solution 3:
If you're not too worried about optimizing your code and just learning then there's also another way to sort it and that's with the bubble sort.
functionreverseArrayInPlace(arr){
for (let i=0;i< arr.length;i++){
for (let j=0;j< arr.length;j++){
if (arr[j]<arr[j+1]) {
let holder=arr[j]
arr[j]=arr[j+1]
arr[j+1]=holder
}
}
}
return arr;
}
console.log(reverseArrayInPlace([1,2,3,4,5])) //[5,4,3,2,1]
If you'd want to reverse an array like [10,9,8,7,6] just flip the less than sign to a greater than sign in the IF, e.g.
if(arr[j]>arr[j+1])
Solution 4:
functionreverseArrayInPlace(array){
for (var i =0; i < Math.floor(array.length/2); ++i){
var temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
return array;
}
var ar = [10, 9, 8, 7, 6];
console.log(reverseArrayInPlace(ar));
THe logic is not the correct, and not return nothing
functionreverseArrayInPlace(array){
for (var i =0; i < Math.floor(array.length/2); ++i){
var temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
returnarray;
}
var ar = [10, 9, 8, 7, 6];
console.log(reverseArrayInPlace(ar));
Post a Comment for "Why Is This Javascript Function Not Reversing The Array?"