Skip to content

Instantly share code, notes, and snippets.

@TheIronDev
Last active December 23, 2015 21:19
Show Gist options
  • Save TheIronDev/6695282 to your computer and use it in GitHub Desktop.
Save TheIronDev/6695282 to your computer and use it in GitHub Desktop.
Following quicksort, I made an implementation of mergesort. :)
var RandomArray = function(size) {
size = size || 10;
var tempArray = [];
for(var count=0,max = size;count<max;count++) {
tempArray.push(~~(Math.random()*100));
}
return tempArray;
};
// Check to see if the array is sorted
Array.prototype.isSorted = function(){
var arrayIndex = this.length;
// Typically I would write a for loop for readability
// But today, we are going for speeeeeeed (yeeeeahhhhhhh)
while(arrayIndex--) {
// Gotta catch that edge case!
if(arrayIndex>0 && this[arrayIndex]<this[arrayIndex-1]) {
return false;
}
}
return true;
};
Array.prototype.mergesort = function(){
if(this.length === 0) {
return [];
} else if(this.length === 1 ){
return this;
} else if(this.length === 2) {
if(this[1] < this[0]) {
return [this[1], this[0]];
}
return this;
}else {
var mergeResult = [], leftItr=0, rightItr=0, left, right;
if(this.length %2 === 0) {
left = this.slice(0, this.length/2);
right = this.slice(-this.length/2);
} else {
left = this.slice(0, this.length/2+1);
right = this.slice(-this.length/2);
}
left = left.mergesort();
right= right.mergesort();
while(leftItr < left.length || rightItr < right.length) {
if(left.length ===leftItr) {
mergeResult.push(right[rightItr]);
rightItr++;
} else if(right.length === rightItr) {
mergeResult.push(left[leftItr]);
leftItr++;
} else if(left[leftItr] < right[rightItr]) {
mergeResult.push(left[leftItr]);
leftItr++;
} else if(right[rightItr] < left[leftItr]) {
mergeResult.push(right[rightItr]);
rightItr++;
} else {
mergeResult.push(left[leftItr]);
mergeResult.push(right[rightItr]);
leftItr++;
rightItr++;
}
}
return mergeResult;
}
};
// Test Cases Helper
function expect(value, expected, message) {
message = message || "Test case: ";
if(value !== expected) {
return message + "false ("+value+" did not match "+expected+")";
} else {
return message + "true";
}
}
(function(){
console.log("*** Testing Sort Functionality ***");
console.log(expect([1,2,3].isSorted(), true, "Sorted array is sorted: "));
console.log(expect([3,2,1].isSorted(), false, "Unsorted array is not sorted: "));
console.log("*** Testing Merge Sort ***");
var temp = new RandomArray();
var sortedArray = temp.mergesort();
console.log("Unsorted: "+temp);
console.log("Sorted: "+sortedArray);
console.log(expect(sortedArray.isSorted(), true, "The sorted array is sorted: "));
})();
@TheIronDev
Copy link
Author

Minor update to the algorithm... left.shift() and right.shift() are much more expensive than storing iterator variables for each.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment