Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added a rough pass at mergesort

  • Loading branch information...
commit 03fb697bfaed68a6c3cb09b5ecb7ecb1fe7695d0 1 parent d620a1c
 █ndr█w h███r authored

Showing 2 changed files with 37 additions and 1 deletion. Show diff stats Hide diff stats

  1. +35 0 mergesort.js
  2. +2 1  tests.html
35 mergesort.js
... ... @@ -0,0 +1,35 @@
  1 +
  2 +Array.implement('mergesort', function(start, end){
  3 +
  4 + if (start == undefined || end == undefined){
  5 + start = 0;
  6 + end = this.length;
  7 + }
  8 +
  9 + if ((end - start) <= 1) return this;
  10 +
  11 + var middle = start + Math.floor((end - start) / 2);
  12 +
  13 + this.mergesort(start, middle);
  14 + this.mergesort(middle, end);
  15 +
  16 + // TODO: try not to use slice...
  17 + var left = this.slice(start, middle),
  18 + right = this.slice(middle, end),
  19 + min;
  20 +
  21 + while (left.length || right.length){
  22 +
  23 + if (left.length && right.length){
  24 + min = (left[0] <= right[0]) ? left.shift() : right.shift();
  25 + } else if (left.length){
  26 + min = left.shift();
  27 + } else if (right.length){
  28 + min = right.shift();
  29 + }
  30 +
  31 + this[start++] = min;
  32 + }
  33 +
  34 + return this;
  35 +});
3  tests.html
@@ -23,7 +23,8 @@
23 23 'insertionsort',
24 24 'shellsort',
25 25 'combsort',
26   - 'cocktailsort'
  26 + 'cocktailsort',
  27 + 'mergesort'
27 28 ].forEach(function(file){
28 29 document.writeln('<script type="text/javascript" src="' + file + '.js"><\/script>');
29 30 });

0 comments on commit 03fb697

Please sign in to comment.
Something went wrong with that request. Please try again.