diff --git a/sort.js b/sort.js new file mode 100644 index 00000000..2a803a39 --- /dev/null +++ b/sort.js @@ -0,0 +1,43 @@ +(function(exports) { + + var foo = (function() { + +function CArray(numElements) { + this.dataStore = []; + this.pos = 0; + this.numElements = numElements; + this.insert = insert; + this.toString = toString; + this.clear = clear; + this.setData = setData; + for (var i = 0; i < numElements; ++i) { + this.dataStore[i] = i; + } +} +function setData() { + for (var i = 0; i < this.numElements; ++i) { + this.dataStore[i] = Math.floor(Math.random() * + (this.numElements+1)); + } +} +function clear() { + for (var i = 0; i < this.dataStore.length; ++i) { + this.dataStore[i] = 0; + } +} +function insert(element) { + this.dataStore[this.pos++] = element; +} +function toString() { + var retstr = ""; + for (var i = 0; i < this.dataStore.length; ++i) { + retstr += this.dataStore[i] + " "; + if (i > 0 && i % 10 == 0) { + retstr += "\n"; + } + } + return retstr; +} +}()); + exports.foo = foo; +})(typeof window === 'undefined' ? module.exports : window); diff --git a/src/sorting/heapsort.js b/src/sorting/heapsort.js index 765adc3a..eef5b232 100644 --- a/src/sorting/heapsort.js +++ b/src/sorting/heapsort.js @@ -18,24 +18,30 @@ * @param {function} cmp Comparison function. */ function heapify(array, index, heapSize, cmp) { + //console.log("Begin heapify: array=" + array + " index=" + index + //+ " heapSize=" + heapSize + " cmp=" + cmp); + var left = 2 * index + 1; var right = 2 * index + 2; var largest = index; + //console.log("left=" + left + " right=" + right + " largest=" + largest); + if (left < heapSize && cmp(array[left], array[index]) > 0) { largest = left; } - + //console.log("largest=" + largest); if (right < heapSize && cmp(array[right], array[largest]) > 0) { largest = right; } - + //console.log("largest=" + largest); if (largest !== index) { var temp = array[index]; array[index] = array[largest]; array[largest] = temp; heapify(array, largest, heapSize, cmp); } + console.log(array); } /** @@ -82,6 +88,7 @@ array[0] = array[i]; array[i] = temp; size -= 1; + console.log(array); heapify(array, 0, size, cmp); } return array; diff --git a/testHeap.js b/testHeap.js new file mode 100644 index 00000000..1cfc24e7 --- /dev/null +++ b/testHeap.js @@ -0,0 +1,31 @@ +/* Test Heapsort Code + * + */ + +function dispArr(arr) { + for (var i = 0; i < arr.length; ++i) { + process.stdout.write(arr[i] + " "); + if (i % 10 == 9) { + process.stdout.write("\n"); + } + } + if (i % 10 != 0) { + process.stdout.write("\n"); + } +} + +var MAX = 50 +var sort = require('./src/sorting/heapsort.js').heapSort; +var values = []; +/*for (var i = 0; i < MAX; ++i) { + values[i] = Math.floor(Math.random() * MAX+1); +}*/ + +values = [40,7,41,13,19,92,51,31]; + +console.log('\nBefore: '); +dispArr(values); +console.log('\nAfter: '); + +dispArr(sort(values)); +