1.堆:一般經過二叉堆,實爲二叉樹的一種,分爲最小堆和最大堆,具備如下性質:java
將根節點最大的堆叫作最大堆或大根堆,根節點最小的堆叫作最小堆或小根堆。this
2.最小堆實現:spa
插入:code
1) 將新插入的元素,放置到隊列的尾部。blog
2) 若該元素小於其父節點,兩個元素互換。(上移操做)隊列
3) 迭代,直至該元素沒有父節點或小於其父節點。class
刪除:二叉樹
1) 移掉頂部的節點。static
2) 將隊末的元素放置到頂部。di
3) 該節點與其子節點中較小的那個比較,若小於它,則交換位置,(下移操做)
4) 迭代,直到葉節點或再也不比其子節點中較小那個大。
java code:
1 package minHeap; 2 3public class MinHeap { 4 private int[] data; 5 6 public MinHeap(int[] data) { 7 this.data = data; 8 } 9 10 public void createHeap() { 11 for (int i = (data.length) / 2 - 1; i >= 0; i--) { 12 heapIfy(i); 13 } 14 } 15 16 public void heapIfy(int value) { 17 int lchild = left(value); 18 int rchild = right(value); 19 int smallest = value; 20 if (lchild < data.length && data[lchild] < data[value]) 21 smallest = lchild; 22 if (rchild < data.length && data[rchild] < data[smallest]) 23 smallest = rchild; 24 if (value == smallest) 25 return; 26 swap(value, smallest); 27 heapIfy(smallest); 28 } 29 30 public int left(int value) { 31 return ((value + 1) << 1) - 1; 32 } 33 34 public int right(int value) { 35 return (value + 1) << 1; 36 } 37 38 public void swap(int i, int j) { 39 int tmp = data[i]; 40 data[i] = data[j]; 41 data[j] = tmp; 42 } 43 44 public void setRoot(int value) { 45 data[0] = value; 46 heapIfy(0); 47 } 48 49 public static void main(String[] args) { 50 int[] value = { 10, 100, 12, 73, 45, 32, 11, 23, 55, 34, 90, 21 }; 51 MinHeap heap = new MinHeap(value); 52 heap.createHeap(); 53 for (int i = 0; i < value.length; i++) { 54 System.out.print(heap.data[i] + " "); 55 } 56 System.out.println(); 57 heap.setRoot(64); 58 for (int i = 0; i < value.length; i++) { 59 System.out.print(heap.data[i] + " "); 60 } 61 System.out.println(); 62 } 63 }