<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
</head>
<body>
<script>
function IndexHeap(data){
this.arr=new Array();
this.reverse=new Array();
for(var i=0;i<data.length;i++){
this.arr[i]=i;
this.reverse[i]=-1;
}
this.count=0;
this.change=function(i,newItem){
data[i]=newItem;
var j=this.reverse[i];
this.shiftUp(j);
this.shiftDown(j);
}
this.size=function(){
return this.count;
};
this.isEmpty=function(){
return this.count==0;
}
this.insert=function(item){
this.arr[this.count]=item;
this.arr[count+1] = count+1;
this.reverse[count] = count+1;
this.shiftUp(this.count);
this.count++;
}
this.extractMax=function(){
var temp=this.arr[0];
this.arr[0]=this.arr[count];
this.reverse[this.arr[0]]=0;
this.reverse[this.arr[count]]=count;
this.count--;
this.shiftDown(0);
return temp;
}
this.shiftDown=function(index){
while(index*2+1<=this.count){
var j=index*2+1;
if(j+1<=this.count&&data[this.arr[j+1]]>data[this.arr[j]]){
j++;
}
if(data[this.arr[j]]<data[this.arr[index]]){
break;
}
var temp=this.arr[j];
this.arr[j]=this.arr[index];
this.arr[index]=temp;
this.reverse[this.arr[index]]=index;
this.reverse[this.arr[j]]=j;
index=j;
}
/*if(index>count||index*2>count||(index*2+1)>count){
return;
}
var left=index*2;
var right=index*2+1;
if(arr[left]>arr[right]){
if(arr[left]>arr[index]){
var temp=arr[left];
arr[left]=arr[index];
arr[index]=temp;
shiftDown[left];
}
}else{
if(arr[right]>arr[index]){
var temp=arr[right];
arr[right]=arr[index];
arr[index]=temp;
shiftDown[right];
}
}*/
}
this.shiftUp=function(index){
var parent=Number.parseInt((index-1)/2);
if(parent<0){
return;
}
if(data[this.arr[index]]>data[this.arr[parent]]){
var temp=this.arr[parent];
this.arr[parent]=this.arr[index];
this.arr[index]=temp;
this.reverse[this.arr[index]]=index;
this.reverse[this.arr[parent]]=parent;
this.shiftUp(parent);
}
}
this.heapify=function(){
this.count=this.arr.length-1;
var n=Number.parseInt((this.count-1)/2);
for(var j=n;j>=0;j--){
this.shiftDown(j);
}
}
//原地堆排序
this.heapsort=function(){
for(var i=this.arr.length-1;i>0;i--){
var temp=this.arr[0];
this.arr[0]=this.arr[i];
this.arr[i]=temp;
this.count--;
this.shiftDown(0);
}
}
this.show=function(){
alert(this.arr);
}
}
var arrEX=[4,1,10,9,3,6,19,12,11,14,48,99,56,45];
var heap=new IndexHeap(arrEX);
heap.heapify();
heap.heapsort();
heap.show();
/*for(var i=0;i<arrEX.length; i++){
heap.insert(arrEX[i]);
}
heap.show();*/
</script>
</body>
</html>