"use strict"; /* * compare heap sort with build to heap sort with sequence of inserts * the different is slight with random input values ( genRandomElts ) * the difference is larger with bad data... unfortunate, worst case * input sequences ( genOrderedElts ) * * bubble sort included for comparison */ myMain(); function myMain() { //var nums= [12,3,51,13,-8.5,25,101,4.3,44,-10,25.3, -17,0,0.01,551,308,17,2]; //var nums= [21,32,-19,4,71,-3,17,0,8,11,54]; //var N=3770000, MAX=900000000; var N=20000000, MAX=900000000; // for bubblesort //var nums = genRandomElts(N,MAX); var nums = genOrderedElts(N); var st, et, sortedNums; alert(N+" elts, Sorting demo... "); st = (new Date()).getTime(); //sortedNums = heapishSortBuild(nums); sortedNums = heapishSortInsert(nums); //sortedNums = bubbleSort(nums); // dont do this on more than // 100,000 items or you will be sorry et = (new Date()).getTime(); alert(et-st + " msec"); } function heapishSortBuild(vals) { var hh = makeNewHeap(); hh.build(vals); //hh.print(); var sVals = []; var s = hh.size(); for (var k=0; k0; k--) { // bubble down, like in delete var temp, done=false; var n=k, c=0; while(!done) { if (this.isLeaf(n)) { done=true; } else { if (this.hasOnlyLC(n)) { c = this.LC(n); } else { c = (this.LCV(n) < this.RCV(n)) ? this.LC(n) : this.RC(n) ; } if (this.elts[n]>this.elts[c]) { temp=this.elts[n]; this.elts[n]=this.elts[c]; this.elts[c]=temp; n = c; } else { done=true; } } } } }, insert: function (val) { this.last++; this.elts[this.last] = val; var n=this.last; var p=this.PN(n); var temp; while ( (p!==0) && (valthis.elts[c]) { temp=this.elts[c]; this.elts[c]=this.elts[n]; this.elts[n]=temp; n = c; } else { done=true; } } } }, LC: function (n) { return 2*n; }, // slot num RC: function (n) { return (2*n)+1; }, // slot num PN: function (n) { return Math.floor(n/2); }, // slot num LCV: function (n) { return this.elts[this.LC(n)]; }, // element val RCV: function (n) { return this.elts[this.RC(n)]; }, // element val PNV: function (n) { return this.elts[this.PN(n)]; }, // element val isLeaf: function (n) { return ( this.LC(n)>this.last && this.RC(n)>this.last ); }, hasOnlyLC: function (n) { return ( this.RC(n)>this.last && this.LC(n)<=this.last ); }, print: function ( ) { alert("heap elts: "+ this.elts.slice(1)); }, } return heap; } //================================================================================== // // bubble sort // //================================================================================== function bubbleUp ( vals ) { var temp; for (var i=0; ivals[i+1]) { temp=vals[i]; vals[i]=vals[i+1]; vals[i+1]=temp; } } return vals; } function bubbleSort ( vals ) { for (var i=0; i