Skip to content

Instantly share code, notes, and snippets.

@GeroSalas
Created May 1, 2018 22:00
Show Gist options
  • Save GeroSalas/c233bb7adbef6faecda51757e1e134ea to your computer and use it in GitHub Desktop.
Save GeroSalas/c233bb7adbef6faecda51757e1e134ea to your computer and use it in GitHub Desktop.
Snail Sort
// 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