// merge sort
// REMOVE these if running in somethign that supports console.log etc
console.log = function (message) {
$("#logger").append("<div>" + message + "</div");
};
console.debug = function (message) {
$("#logger").append("<div class='title'>" + message + "</div");
};
var unsorted = [0,3, 6, 4, 5, 8, 1, 7, 9, 2];
// I'm using a closure/module here so that I can declare merge once and not evertime I call the internal sort
var mergeSort = (function () {
var merge = function (sortedA, sortedB) {
console.debug("merging");
console.log(sortedA);
console.log(sortedB);
var toReturn = [];
var itA = 0,
itB = 0,
Alength = sortedA.length,
Blength = sortedB.length;
while (itA < Alength && itB < Blength) {
if (sortedB[itB] < sortedA[itA]) {
toReturn.push(sortedB[itB++]);
} else {
toReturn.push(sortedA[itA++]);
}
}
toReturn = toReturn.concat(sortedB.slice(itB)).concat(sortedA.slice(itA));
return toReturn;
};
var sort = function (toSort) {
var arlength = toSort.length || toSort.end - toSort.start;
var midpoint = toSort.length ? Math.round(arlength / 2) : (Math.round((toSort.end-toSort.start)/ 2)+toSort.start);
var toSort = toSort.length ? toSort : toSort.array;
var start = toSort.start || 0;
var end = toSort.end || arlength;
if (arlength > 1) {
var A = {array:toSort, start:start, end:midpoint};
var B = {array:toSort, start:midpoint, end:arlength};
return merge(sort(A), sort(B));
}
return toSort;
};
return sort;
})();
var result = mergeSort(unsorted);
console.debug("FINISHED");
console.debug(result);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.