Java heap data structure



public class MaxHeap {
private int[] data;
private int count;
private int capacity;


public MaxHeap(int capacity){
this.capacity=capacity;
data=new int[capacity+1];
count=0;
}
public void insert(int n)
{
data[++count]=n;
shiftUp(count);
}

private void shiftUp(int n) {


while(n>1&&data[n/2]<data[n])
{
swap(data,n/2,n);
n=n/2;
}
}
int size public () {
return COUNT;
}
public Boolean isEmpty () {
return COUNT == 0;
}
public int getMax () // copy a maximum value
{
Assert ( COUNT> 0);
return Data [ . 1];
}
public extractMax int () // directly taken out of the maximum value, there is no heap
{
Assert ( Count - . 1> 0);
int max = Data [ . 1];
the swap ( Data, COUNT, . 1);
count--;
shiftDown ( . 1);
return max;
}

Private void shiftDown ( int I) {
J * = I int 2; // find the left node the while (J <= COUNT) // children if they exist, will continue to go down, regardless of whether there is a right node { IF (J + . 1 <= COUNT && Data [J + . 1]> Data [J]) // if there is a right node, comparing the left and right nodes { IF ( Data [J + . 1]> Data [I]) { the swap ( Data, I, J + . 1); I = J + . 1; = J 2 * I; } the else BREAK; } the else { IF ( Data [J]> Data [I]) { the swap ( Data, I, J); I = J; J = 2 * I; }





















else
break;
}
}

}

public void swap(int[] arr,int l,int r)
{
int temp=arr[l];
arr[l]=arr[r];
arr[r]=temp;
}

public static void main(String[] args) {
MaxHeap maxHeap=new MaxHeap(100);
int N=100;
int M=100;
for(int i=1;i<=100;i++)
{
maxHeap.insert((int) (Math.random()*M));
}
int[] arr=new int[N];
for(int i=0;i<N;i++)
{
arr[i]=maxHeap.extractMax();
}
for (int i = 0; i <N ; i++) {
System.out.println(arr[i]);
}
}

}

Guess you like

Origin www.cnblogs.com/cold-windy/p/11199768.html