Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added a rough pass at mergesort

  • Loading branch information...
commit 03fb697bfaed68a6c3cb09b5ecb7ecb1fe7695d0 1 parent d620a1c
 █ndr█w h███r authored
Showing with 37 additions and 1 deletion.
  1. +35 −0 mergesort.js
  2. +2 −1  tests.html
35 mergesort.js
View
@@ -0,0 +1,35 @@
+
+Array.implement('mergesort', function(start, end){
+
+ if (start == undefined || end == undefined){
+ start = 0;
+ end = this.length;
+ }
+
+ if ((end - start) <= 1) return this;
+
+ var middle = start + Math.floor((end - start) / 2);
+
+ this.mergesort(start, middle);
+ this.mergesort(middle, end);
+
+ // TODO: try not to use slice...
+ var left = this.slice(start, middle),
+ right = this.slice(middle, end),
+ min;
+
+ while (left.length || right.length){
+
+ if (left.length && right.length){
+ min = (left[0] <= right[0]) ? left.shift() : right.shift();
+ } else if (left.length){
+ min = left.shift();
+ } else if (right.length){
+ min = right.shift();
+ }
+
+ this[start++] = min;
+ }
+
+ return this;
+});
3  tests.html
View
@@ -23,7 +23,8 @@
'insertionsort',
'shellsort',
'combsort',
- 'cocktailsort'
+ 'cocktailsort',
+ 'mergesort'
].forEach(function(file){
document.writeln('<script type="text/javascript" src="' + file + '.js"><\/script>');
});
Please sign in to comment.
Something went wrong with that request. Please try again.