package datastructure;
class Heap{
int[] data;
int length;
}
class HeapOp{
public Heap create(Heap heap){
int n = heap.length;
for(int i = (n - 1) / 2; i >= 1; i--)
shiftDown(heap, i);
return heap;
}
public void shiftDown(Heap heap, int i){
int n = heap.length;
while(2*i < n){
int child = 2 * i;
if(2*i+1 < n && heap.data[2*i+1] > heap.data[2*i])
child++;
if(heap.data[child] > heap.data[i]){
swap(heap.data, i, child);
i = child;
}else
return;
}
}
public void swap(int[] data, int i, int j){
int t = data[i];
data[i] = data[j];
data[j] = t;
}
public void print(Heap heap){
for(int i = 1; i < heap.length; i++){
System.out.print(heap.data[i] + " ");
}
System.out.println();
}
public void insert(Heap heap, int key){
int n = heap.length;
int[] data = heap.data;
int i = n;
while(i != 1 && key > data[i/2]){
data[i] = data[i/2];
i /= 2;
}
data[i] = key;
heap.length++;
}
public void delete(Heap heap){
int n = heap.length;
heap.data[1] = heap.data[n - 1];
heap.length--;
shiftDown(heap, 1);
}
}
public class Heap1 {
public static void main(String[] args) {
//最大堆
//堆从1开始存储数据
HeapOp h= new HeapOp();
int[] init = {0, 2, 14, 10, 20, 15};
int[] data = new int[100];
for(int i = 1; i < init.length; i++)
data[i] = init[i];
//初始化Heap
Heap initHeap = new Heap();
initHeap.length = init.length;
initHeap.data = data;
//创建
System.out.println("build heap :");
Heap heap = h.create(initHeap);
h.print(heap);
//插入
System.out.println("insert heap :");
int key = 13;
h.insert(heap, key);
h.print(heap);
//删除 最大元素
System.out.println("delete heap :");
h.delete(heap);
h.print(heap);
}
}
堆的基本操作
最新推荐文章于 2021-03-08 11:18:50 发布