Skip to content

Instantly share code, notes, and snippets.

@kariudo
Created April 25, 2014 13:21
Show Gist options
  • Save kariudo/11289370 to your computer and use it in GitHub Desktop.
Save kariudo/11289370 to your computer and use it in GitHub Desktop.
Snail Sort
snail = function(array) {
var result = [];
var n=array.length;
var x=n;
var y=n;
if(n==1){
return array[0];
}
while(y>1){
for(j=0;j<y;j++){
result.push(array[0][j]);
}
array.splice(0,1);
y--;
for(j=0;j<y;j++){
result.push(array[j][y]);
array[j].splice(y);
}
x--;
for(j=x-1;j>=0;j--){
result.push(array[y-1][j]);
}
array.splice(y-1);
x--;
for(j=y-1;j>0;j--){
result.push(array[j-1][0]);
array[j-1].splice(0,1);
}
y--;
if(y==1&&x==1){
result.push(array[0][0]);
}
}
return result;
}
/*array = [[1,2,3],
[8,9,4],
[7,6,5]]
*/
array=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]];
console.log('result:'+snail(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment