DEV Community

Discussion on: Daily Challenge #59 - Snail Sort

Collapse
 
anders profile image
Anders • Edited

A different take, this one might not appear as elegant, but it is quite a lot faster than the previous variants:

function snail(m) {

if (m.length <= 1) { return m; }

var max = { x: m.length - 1, y: m.length - 1 };
var min = { x: 0, y: 0 };
var current = { x: 0, y: 0 };
var direction = { x: 1, y: 0 };
var output = [];
var resultSize = m.length * m.length;

while (output.length != resultSize) {

    output.push(m[current.y][current.x]);

    current.x += direction.x;
    current.y += direction.y;

    if (current.x > max.x) { 

        direction.x = 0; direction.y = 1; min.y += 1; current.x = max.x; current.y += 1;

    } else if (current.x < min.x) { 

        direction.x = 0; direction.y = -1; max.y -= 1; current.x = min.x; current.y -= 1;

    } else if (current.y > max.y) { 

        direction.x = -1; direction.y = 0; max.x -= 1; current.y = max.y; current.x -= 1;

    } else if (current.y < min.y) { 

        direction.x = 1; direction.y = 0; min.x += 1; current.y = min.y; current.x += 1;
    }
}

return output;
}
Collapse
 
anders profile image
Anders • Edited

So there was supposed to be an image attached, but it doesn't seem to work, anyhow, for those curious JSBench.me gives the following results:

Above one
2,508,265 ops/s ±0.46%

Chris Achards
411,247 ops/s ±1.04%

La blattes
364,899 ops/s ±3.35%

(Firefox, Windows)

snail([[1, 2, 3, 4, 5, 6],
[20, 21, 22, 23, 24, 7],
[19, 32, 33, 34, 25, 8],
[18, 31, 36, 35, 26, 9],
[17, 30, 29, 28, 27, 10],
[16, 15, 14, 13, 12, 11]]);