// merge sort
// 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) {
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;
var midpoint = Math.round(arlength / 2);
if (toSort.length > 1) {
// just here to illistrate the step, these should be remove or renamed and moved to the top of the function
// MEMOP - slicing creates new arrays, performign this in place would be lighter
var A = toSort.slice(0, midpoint);
var B = toSort.slice(midpoint, arlength);
return merge(sort(A), sort(B));
}
return toSort;
};
return sort;
})();
var bubbleSort = (function () {
var swaps = 0;
var swap = function (arr, s, e) {
swaps++;
var temp = arr[s];
arr[s] = arr[e];
arr[e] = temp;
};
var sort = function (toSort) {
var passes = 0;
var i1 = 0;
var i2;
var pointer = 0;
var l = toSort.length;
for (; i1 < l; i1++) {
pointer = 0;
var remainderLe = l - i1;
for (i2=pointer; i2 < remainderLe; i2++) {
if (toSort[i2] > toSort[i2 + 1]) {
swap(toSort, i2, i2 + 1);
}
passes++;
pointer++;
}
if(swaps===0)
...
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.