拙劣算法:堆建立
2019-05-14 本文已影响0人
我在等你回复可你没回
说明
某一个节点i父节点,子节点公式:
父节点=(i -1)/2
左子节点=2i+1
右子节点=2i+1
heapify用于就某一个i节点搞堆,用到递归,如果存在交换,被交换的点要递归搞堆。
buildHeap用来建立堆,怎么建立的呢,从最后一个节点往上执行heapify操作。想想为什么要这样做??因为从下往上,可以确保下面的先搞成堆,上面的就可以用下面的了。
int[] arr = {4,10,3,5,1,2,100};
int[] heap = buildHeap(arr,7);
for (int i = 0; i < heap.length; i++) {
Log.i("findnum"," " + heap[i]);
}
private int[] heapify(int [] tree, int size,int i) {
int left = 2 * i + 1;
int right = 2 * i + 2;
if (right > size -1 || left > size -1) {
return tree;
}
int max = i;
if (tree[left] > tree[i]) {
max = left;
}
if (tree[right] > tree[i]) {
max = right;
}
if (max != i) {
int temp = tree[i];
tree[i] = tree[max];
tree[max] = temp;
return heapify(tree, size, max);
}
return tree;
}
private int[] buildHeap(int [] tree, int size) {
int round = 1;
for (int i = size -1; i >= 0 ; i--) {
Log.i("findnum","rount :" + round + "try heap:" + tree[i]);
tree = heapify(tree,size,i);
for (int j = 0; j < tree.length; j++) {
Log.i("findnum"," " + tree[j]);
}
round++;
}
return tree;
}
参考:https://www.bilibili.com/video/av47196993/?redirectFrom=h5