Mergesort implementation complete.

master
ben-burlingham 10 years ago
parent 78078f1a65
commit 71a8ce0db0
  1. 2
      index.html
  2. 55
      js/mergesort.js

@ -115,7 +115,7 @@
console.log('SHUFFLED: ' + b.join(','));
var ordered = Object.create(shuffled);
MS.sort(ordered, 0, ordered.length - 1);
var ordered = MS.sort(ordered, 0, ordered.length - 1);
var c = []
ordered.forEach(function(obj0) {
c.push(obj0.value);

@ -25,29 +25,54 @@ Mergesort.prototype.addInstruction = function(operation, left, right, mid) {
});
};
var count = 0;
var dump = function(arr) {
var d = [];
arr.forEach(function(obj) {
d.push(obj.value);
})
return d.join(',');
}
/**
*
*/
Mergesort.prototype.sort = function(arr, start, end) {
count++;
if (count > 30) {
console.error('count exceeded');
return;
}
if (start >= end) {
this.addInstruction('single', start, end, null);
return;
if (start === end) {
this.addInstruction('single', start);
return new Array(arr[start]);
}
var mid = start + Math.floor((end - start) / 2);
// this.addInstruction('init', start, end, mid);
var arr1 = this.sort(arr, start, mid);
var arr2 = this.sort(arr, mid + 1, end);
var result = this.merge(arr1, arr2);
return result;
};
/**
*
*/
Mergesort.prototype.merge = function(arr1, arr2) {
var result = [];
while (arr1.length > 0 || arr2.length > 0) {
if (arr1.length === 0) {
result.push(arr2.shift());
}
else if (arr2.length === 0) {
result.push(arr1.shift());
}
else if (arr1[0].value <= arr2[0].value) {
result.push(arr1.shift());
}
else {
result.push(arr2.shift());
}
}
this.sort(arr, start, mid);
this.sort(arr, mid + 1, end);
return;
return result;
};

Loading…
Cancel
Save