二叉堆的数组实现

package com.hengyunsoft.test;

import java.util.Comparator;
import java.util.Random;

import edu.emory.mathcs.backport.java.util.Arrays;

public class PriorityArray<E> {

/**
* 当前已用大小
*/
private int size;

private Object[] e;

private Comparator<E> comparator;

public PriorityArray(int capacity, Comparator<E> comparator) {

e = new Object[capacity];
this.comparator = comparator;
size = 0;
}

/**
*
* @param obj
*            not null
*/
public void put(E obj) {

if (obj == null)
return;
e[size] = obj;
swapFZ(size);
++size;
}

private void swapFZ(int children) {
if (children <= 0) {
return;
}

// 找父节点
// 左:left = 2p+1
// 右:left = 2p+2
int p;
if ((children & 1) == 1) {
// 奇数
p = (children - 1) >>> 1;
} else {
// 偶数
p = (children - 2) >>> 1;
}

System.out.print("孩子:" + children + " value :" +(E) e[children]);
System.out.print("    父亲:" + p + " value :" +(E) e[p]);
if (comparator.compare((E) e[children], (E) e[p]) < 0) {
swap(children, p);
System.out.println("进行交互");
swapFZ(p);
} else {
System.out.println("不会进行交互");
}
}

private void swap(int x, int y) {
final Object temp = e[x];
e[x] = e[y];
e[y] = temp;
}

public static void main(String[] args) {

System.out.print(1 << 1 + 1);

PriorityArray<Integer> arr = new PriorityArray<>(100,
new Comparator<Integer>() {

@Override
public int compare(Integer x, Integer y) {
return Integer.compare(x, y);
}
});

Random random = new Random();

for (int i = 0; i < arr.e.length; i++) {
arr.put(random.nextInt(10000));
}



for (int j = 0,nextFlag=1,i=0; j < arr.size; j++) {
if(j < nextFlag){
System.out.print(arr.e[j] + "   ");

}else {

System.out.println();
System.out.print(arr.e[j] + "   ");

nextFlag += 2 << i;
i++;
}
}
System.out.println();
System.out.println(Arrays.toString(arr.e));
for (int i = 0; i < arr.e.length; i++) {
System.out.print(arr.pop() + "   ");
}
}

public E pop() {

if (size == 0)
return null;
E result = (E) e[0];

e[0] = e[size - 1];
swapZF(0);
--size;
return result;
}

private void swapZF(int p) {

final int left = (p << 1) + 1;
final int right = left + 1;
if (left >= size) {
return;
}
if (right >= size) {
if (comparator.compare((E) e[left], (E) e[p]) < 0) {
swap(left, p);
swapZF(left);
}
return;
}

int minIndex = right;
if (comparator.compare((E) e[left], (E) e[right]) < 0) {
minIndex = left;
}

if (comparator.compare((E) e[minIndex], (E) e[p]) < 0) {
swap(minIndex, p);
swapZF(minIndex);
}
}
}

猜你喜欢

转载自1064319393.iteye.com/blog/2390258