Created
November 21, 2023 06:27
-
-
Save akbarjondev/3ffc3f4c3de7fc2eaa376b06e7470602 to your computer and use it in GitHub Desktop.
Reverse in place algorithm for arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverseInPlace(arr) { | |
let length = arr.length, | |
middle = Math.floor(length / 2), | |
temp = null | |
for(let i = 0; i < middle; i++) { | |
temp = arr[i] | |
arr[i] = arr[arr.length - 1 - i] | |
arr[arr.length - 1 - i] = temp | |
} | |
} | |
const arr1 = [-1, 0, 11, 9] | |
reverseInPlace(arr1) | |
console.log(arr1) // [9, 11, 0, -1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment