Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Created November 21, 2023 06:27
Show Gist options
  • Save akbarjondev/3ffc3f4c3de7fc2eaa376b06e7470602 to your computer and use it in GitHub Desktop.
Save akbarjondev/3ffc3f4c3de7fc2eaa376b06e7470602 to your computer and use it in GitHub Desktop.
Reverse in place algorithm for arrays
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