Skip to content

Instantly share code, notes, and snippets.

@aessam
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save aessam/c0dd6cec10c374a1981d to your computer and use it in GitHub Desktop.

Select an option

Save aessam/c0dd6cec10c374a1981d to your computer and use it in GitHub Desktop.
JS code the generates random array of numbers and sort it using merge sort without using recursive function call
// Inspired by the game 2048 :D
function merge(left, right) {
var result = [];
while(left.length || right.length) {
if(left.length && right.length) {
if(left[0]<right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
} else if (left.length) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result;
}
function generateRandomList(num){
var gen = {};
var arr = [];
var base = parseInt("10" + Array(num.toString().length).join("0"));
var num = parseInt(num);
for(n=0;Object.keys(gen).length<num;n++){
rand = parseInt(Math.random()*base);
if(gen[rand]==undefined){
gen[rand] = "";
arr.push(rand);
}
}
function comparator(left, right) {
if (left > right) return 1
else if (left < right) return -1
else if (left == right) return 0
}
return arr;
}
var originalArray = generateRandomList(100);
loopSize = originalArray.length/2;
stack = [];
for(n=0;n<loopSize;n++){
var aIdx = n*2 ;
left = originalArray.slice(aIdx,aIdx+1);
aIdx++;
right = originalArray.slice(aIdx,aIdx+1);
merged = merge(left,right);
stack.push(merged);
while(stack.length>=2){
if(stack[stack.length-1].length==stack[stack.length-2].length){
left = stack.pop();
right = stack.pop();
stack.push(merge(left,right));
}else{
break;
}
}
}
while(stack.length>=2){
left = stack.pop();
right = stack.pop();
stack.push(merge(left,right));
}
console.log(JSON.stringify(stack[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment