Last active
October 19, 2018 23:44
-
-
Save jesus-seijas-sp/ab039b8ac10eed65f40c554ecd27242e to your computer and use it in GitHub Desktop.
array reverse
This file contains 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
const numElements = 10000; | |
const numLoops = 100000; | |
const arr = []; | |
for (let i = 0; i < numElements; i += 1) { | |
arr.push(i); | |
} | |
function reverse1(a) { | |
const reversed = []; | |
const aLength = a.length; | |
if (aLength >= 0) { | |
for (let i = aLength; i >= 0; i -= 1) { | |
reversed.push(a[i]); | |
} | |
return reversed; | |
} | |
return a; | |
} | |
function reverse2(a) { | |
for (let l = 0, m = a.length / 2, r = a.length - 1; l < m; l += 1, r -= 1) { | |
const t = a[l]; | |
a[l] = a[r]; | |
a[r] = t; | |
} | |
return a; | |
} | |
function reverse3(a) { | |
const result = new Array(a.length); | |
for (let i = 0, r = a.length - 1; r >= 0; i += 1, r -= 1) { | |
result[i] = a[r]; | |
} | |
return result; | |
} | |
console.time('Method 1'); | |
for (let i = 0; i < numLoops; i += 1) { | |
reverse1(arr); | |
} | |
console.timeEnd('Method 1'); | |
console.time('Method 2'); | |
for (let i = 0; i < numLoops; i += 1) { | |
reverse2(arr); | |
} | |
console.timeEnd('Method 2'); | |
console.time('Method 3'); | |
for (let i = 0; i < numLoops; i += 1) { | |
reverse3(arr); | |
} | |
console.timeEnd('Method 3'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment