堆和二叉堆的实现和特性( 四 )

JavaScript 版本// JavaScriptclass BinaryHeap {  constructor(compare) {    this.data = [];    this.compare = compare;  }  insert(value) {    this.insertAt(this.data.length, value);  }  insertAt(index, value) {    this.data[index] = value;    // 对比当前节点与其父节点,如果当前节点更小就交换它们    while (index > 0 && this.compare(value, this.data[Math.floor((index - 1) / 2)]) < 0) {      this.data[index] = this.data[Math.floor((index - 1) / 2)];      this.data[Math.floor((index - 1) / 2)] = value;      index = Math.floor((index - 1) / 2);    }  }  delete(index) {    if (this.data.length === 0) return;    let value = this.data[index];    let i = index;    // fix heap    while (i < this.data.length) {      let left = i * 2 + 1;      let right = i * 2 + 2;      // 没有左子节点      if (left >= this.data.length) break;      // 没有右子节点      if (right >= this.data.length) {        this.data[i] = this.data[left];        i = left;        break;      }      // 比较左右子节点的大小,更小的补到父节点      if (this.compare(this.data[left], this.data[right]) < 0) {        this.data[i] = this.data[left];        i = left;      } else {        this.data[i] = this.data[right];        i = right;      }    }    // 查看最后的空位是不是最后的叶子节点    if (i < this.data.length - 1) {      this.insertAt(i, this.data.pop());    } else {      this.data.pop();    }    return value;  }  printHeap() {    console.log("nHeap = ");    console.log(this.data);  }}let maxHeap = new BinaryHeap((a, b) => b - a);maxHeap.insert(10);maxHeap.insert(4);maxHeap.insert(9);maxHeap.insert(1);maxHeap.insert(7);maxHeap.insert(5);maxHeap.insert(3);maxHeap.printHeap();maxHeap.delete(5);maxHeap.printHeap();maxHeap.delete(2);maxHeap.printHeap();Python 版本Pythonimport sys class BinaryHeap:       def __init__(self, capacity):         self.capacity = capacity         self.size = 0        self.Heap = [0]*(self.capacity + 1)         self.Heap[0] = -1 * sys.maxsize         self.FRONT = 1      def parent(self, pos):         return pos//2      def leftChild(self, pos):         return 2 * pos       def rightChild(self, pos):         return (2 * pos) + 1      def isLeaf(self, pos):         if pos >= (self.size//2) and pos <= self.size:             return True        return False      def swap(self, fpos, spos):         self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos]       def heapifyDown(self, pos):           if not self.isLeaf(pos):             if (self.Heap[pos] > self.Heap[self.leftChild(pos)] or                self.Heap[pos] > self.Heap[self.rightChild(pos)]):                   if self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]:                     self.swap(pos, self.leftChild(pos))                     self.heapifyDown(self.leftChild(pos))                   else:                     self.swap(pos, self.rightChild(pos))                     self.heapifyDown(self.rightChild(pos))       def insert(self, element):         if self.size >= self.capacity :             return        self.size+= 1        self.Heap[self.size] = element           current = self.size           while self.Heap[current] < self.Heap[self.parent(current)]:             self.swap(current, self.parent(current))             current = self.parent(current)       def Print(self):         for i in range(1, (self.size//2)+1):             print(" PARENT : "+ str(self.Heap[i])+" LEFT CHILD : "+                                 str(self.Heap[2 * i])+" RIGHT CHILD : "+                                str(self.Heap[2 * i + 1]))        def minHeap(self):           for pos in range(self.size//2, 0, -1):             self.heapifyDown(pos)       def delete(self):           popped = self.Heap[self.FRONT]         self.Heap[self.FRONT] = self.Heap[self.size]         self.size-= 1        self.heapifyDown(self.FRONT)         return popped     def isEmpty(self):        return self.size == 0            def isFull(self):         return self.size == self.capacityif __name__ == "__main__":           print('The minHeap is ')     minHeap = BinaryHeap(5)    minHeap.insert(5)     minHeap.insert(3)     minHeap.insert(17)     minHeap.insert(10)     minHeap.insert(84)     minHeap.insert(19)     minHeap.insert(6)     minHeap.insert(22)     minHeap.insert(9)     minHeap.minHeap()       minHeap.Print()     print("The Min val is " + str(minHeap.delete())) 


推荐阅读