Created
May 1, 2018 22:00
-
-
Save GeroSalas/c233bb7adbef6faecda51757e1e134ea to your computer and use it in GitHub Desktop.
Snail Sort
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
// Snail Sort | |
snail = (array) => { | |
const result = [] | |
const n = array.length | |
let x = n // column pointer | |
let y = n // row pointer | |
if (n === 1) { | |
return array[0] // single value | |
} | |
while (y > 1) { | |
// right | |
for (let i=0; i<y; i++) { | |
result.push(array[0][i]) | |
} | |
array.splice(0, 1) | |
y-- | |
// down | |
for (let i=0; i<y; i++) { | |
result.push(array[i][y]) | |
array[i].splice(y) | |
} | |
x-- | |
// left | |
for (let i=x-1; i>=0; i--) { | |
result.push(array[y-1][i]) | |
} | |
array.splice(y-1) | |
x-- | |
// up | |
for (let i=y-1; i>0; i--) { | |
result.push(array[i-1][0]) | |
array[i-1].splice(0, 1) | |
} | |
y-- | |
if (y === 1 && x === 1) { | |
result.push(array[0][0]) // last element | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment