var unsorted = [9, 8, 7, 12, 4, 9, 7, 6, 5, 4, 3, 2]; // Array to sort
function mergeQuater(arr) { // Take a quater of unsorted array
var quater = (arr.length / 4).toFixed(); // Search a quater of unsorted array
return mergeSort(arr.slice(0, quater)).concat(arr.slice(quater)) // Concet method add 75% of array to other 25% of sorted
}
function mergeSort(arr) {
if (arr.length <= 1) { // If aaray less then 1
return arr; // Return it
}
var mid = (arr.length / 2).toFixed(), // Search the middle of 25% of array
left = mergeSort(arr.slice(0, mid)), // Left part
right = mergeSort(arr.slice(mid)), // Right part
result = [];
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) { // If left item more then right
result.push(left.shift()); // Push left to result and remove it
} else {
result.push(right.shift()); // Push right to result and remove it
}
}
if (left.length > 0) { // If something left in our arrays (left or right)
result.push(left); // Push residue of left to the end of result
} else {
result.push(right); // Push residue of right to the end of result
}
return result; // Return result
}
alert(mergeQuater(unsorted));
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.