Javascript Array heapSort()

Description

Javascript Array heapSort()

Array.prototype.heapSort = function(){
 var i, tmp, len = this.length - 1;
 for(i = parseInt(len/2); i >= 1; i--)
  this.createHeap(i, len);//  w w w.j a v  a 2  s. c  om
 for(i = len; i >= 2; i--){
  tmp = this[1];
  this[1] = this[i];
  this[i] = tmp;
  this.createHeap(1, i - 1);
 }
 return this;
}

var arr = [1, 6, 9, 4, 11];
var nArr = arr.heapSort();
console.log(nArr);

Javascript Array heapSort()

Array.prototype.heapSort=function(){
  this.buildMaxHeap();/*from  www.  j  a  v  a2 s .c o m*/
  for(var i=this.length-1;i>0;i--){
    this.swap(0,i);
    this.heapAdjust(0,i);
  }

  return this;
};

Array.prototype.heapAdjust=function(i,j){
  var largest=i;
  var left=2*i+1;
  var right=2*i+2;

  if(left<j&&this[largest]<this[left]){
    largest=left;
  }

  if(right<j&&this[largest]<this[right]){
    largest=right;
  }

  if(largest!=i){
    this.swap(i,largest);
    this.heapAdjust(largest,j);
  }
};
Array.prototype.buildMaxHeap=function(){
  for(var i=Math.floor(this.length/2)-1;i>=0;i--){
    this.heapAdjust(i,this.length);
  }
};

Array.prototype.swap=function(i,j){
  var tmp=this[i];
  this[i]=this[j];
  this[j]=tmp;
};

var a=new Array();
[].push.apply(a,[2,3,89,57,23,72,43,105,6,4,5,7,8,9]);
console.log(a.heapSort());

/**
 * Created by Administrator on 2017/7/6 0006.
 */



PreviousNext

Related