package com.guge.test.heap; import java.util.Random; /** * Created by guugangzhu on 2017/6/4. */ public class Heap { private Node[] heapArray; private int maxSize; private int currentSize; public static void main(String[] args) { Heap heap=new Heap(20); Random random=new Random(); for (int i = 0; i <20 ; i++) { heap.insert(random.nextInt(500)); } heap.displayHeap(); } public Heap(int size){ this.maxSize=size; currentSize=0; heapArray=new Node[size]; } public boolean insert(int key){ if(currentSize==maxSize) return false; Node newNode=new Node(key); heapArray[currentSize]=newNode; trickleUp(currentSize++); return true; } public Node remove(){ if(isEmpty()){ System.out.println("heap is empty"); return null; } Node root=heapArray[0]; heapArray[0]=heapArray[--currentSize]; trickleDown(0); return root; } private void trickleUp(int index){ int parent=(index-1)/2; Node bottom=heapArray[index]; while (index>0&&heapArray[parent].getKey()<bottom.getKey()){ heapArray[index]=heapArray[parent]; index=parent; parent=(parent-1)/2; } heapArray[index]=bottom; } private void trickleDown(int index){ int largerChild; Node top=heapArray[index]; while (index<currentSize/2){ int leftChild=2*index+1; int rightChild=leftChild+1; if(rightChild<currentSize&&heapArray[leftChild].getKey()<heapArray[rightChild].getKey()) largerChild=rightChild; else largerChild=leftChild; if(top.getKey()>=heapArray[largerChild].getKey()) break; heapArray[index]=heapArray[largerChild]; index=largerChild; } heapArray[index]=top; } public boolean change(int index,int newValue){ if(index<0||index>=currentSize) return false; int oldValue=heapArray[index].getKey(); heapArray[index].setKey(newValue); if(oldValue>newValue){ trickleDown(index); }else trickleUp(index); return true; } public boolean isEmpty(){ return currentSize==0; } public void displayHeap(){ System.out.print("heapArray: "); for (int i = 0; i < currentSize; i++) { if(heapArray[i]!=null) System.out.print(heapArray[i].getKey()+" "); else System.out.print("-- "); } System.out.println(); int nBlanks=32; int itemPerRow=1; int column=0; int j=0; String dots="................."; System.out.println(dots+dots); while (currentSize>0){ if(column==0) for (int i = 0; i < nBlanks; i++) { System.out.print(" "); } System.out.print(heapArray[j].getKey()); if(++j==currentSize) break; if(++column==itemPerRow){ nBlanks/=2; itemPerRow*=2; column=0; System.out.println(); }else { for (int i = 0; i < nBlanks*2-2; i++) { System.out.print(" "); } } } } } class Node{ private int iData; public Node(int data){ iData=data; } public int getKey(){ return iData; } public void setKey(int key){ this.iData=key; } }
java 堆
最新推荐文章于 2024-05-28 11:18:00 发布