创建大顶堆
/*-----建造最大堆------*/ // 创建堆 function CreateHeap(MaxSize,MaxData,initialData) { this.MaxSize = MaxSize; this.Heap = initialData; if(!initialData) { this.Heap = new Array(); // 可以传入自定义数组 生成大顶堆 this.Heap[0] = MaxData // 定义" 哨兵 " 为大于堆中所有可能元素的值 } this.BuildHeap = CreateHeap.BuildHeap this.PercDown = CreateHeap.PercDown } CreateHeap.PercDown = function(num) { let parent, child, element; element = this.Heap[num]; for(parent=num; parent*2 + 1 <= this.Heap.length-1; parent=child) { child = parent*2 + 1; if((child != this.Heap.length-1) && (this.Heap[child] < this.Heap[child+1])) { child++ } if(element > this.Heap[child]) { break; } else { this.Heap[parent] = this.Heap[child] } } this.Heap[parent] = element; console.log(this.Heap); } CreateHeap.BuildHeap = function() { let len = this.Heap.length - 2; // 由于有 0 存在 ,所以减去2 来找到父节点 for(let i=Math.floor(len / 2); i>=0; i--) { this.PercDown(i); } } let arr = [14,16,15,8,11,18,13] let heap = new CreateHeap(8,1000,arr); heap.BuildHeap() console.log(heap.Heap);
深度思考,全面总结,综合发展!!