堆数据结构
堆是一颗完全二叉树,所以其往往用数组来实现。堆中的数据是局部有序的,这种有序是父结点与子结点之间的有序。
有两种不同的堆
最大值堆的性质是任意一个结点的值都大于或等于任意一个子结点存储的值。
最小值堆的性质是任意一个结点的值都小于或等于任意一个结点存储的值。
这里实现最大值堆
package binaryTree;
public class MaxHeap {
private Object[] heap;
private int size;
private int n;
private void siftDown(int pos)
{
while(!isLeaf(pos))
{
int j = leftChild(pos);
int rc = rightChild(pos);
if((rc < n) && ((int)heap[j] < (int)heap[rc]))
{
j = rc;
}
if((int)heap[pos] >= (int)heap[j])
return;
swap(heap,pos,j);
pos = j;
}
}
private void swap(Object[] obj,int i,int j)
{
Object temp;
temp = obj[i];
obj[i] = obj[j];
obj[j] = temp;
}
public MaxHeap(Object[] heap,int size,int n)
{
this.heap = heap;
this.size = size;
this.n = n;
}
public int heapSize()
{
return n;
}
public boolean isLeaf(int pos)
{
return (pos >= n/2) && (pos < n);
}
public int leftChild(int pos)
{
return 2*pos + 1;
}
public int rightChild(int pos)
{
return 2*pos + 2;
}
public int parent(int pos)
{
return (pos - 1)/2;
}
public boolean insert(Object obj)
{
if(n >= size)
return false;
int curr = n++;
heap[curr] = obj;
while((curr != 0) && ((int)heap[curr] > (int)heap[parent(curr)]))
{
swap(heap,curr,parent(curr));
curr = parent(curr);
}
return true;
}
public Object removeMax()
{
if(n == 0)
return false;
swap(heap,0,--n);
if(n != 0)
siftDown(0);
return heap[n];
}
public Object remove(int pos)
{
if((pos < 0) || (pos >= n))
{
return null;
}
swap(heap,pos,--n);
while((pos != 0) && (int)heap[pos] > (int)heap[parent(pos)])
{
swap(heap,pos,parent(pos));
}
siftDown(pos);
return heap[n];
}
public void buildHeap()
{
for(int i = n/2 - 1;i >= 0;i--)
{
siftDown(i);
}
}
public void print()
{
for(int i = 0;i < n;i++)
{
System.out.print(heap[i] + " ");
}
System.out.println();
}
public static void main(String[] args)
{
Object[] a = {4,2,45,56,23,43,6567};
MaxHeap mh = new MaxHeap(a,20,a.length);
mh.print();
mh.buildHeap();
mh.print();
}
}
请无视main函数