堆排序代码
package chap6; public class Heap {//堆存在数组中 private int heapsize; public void maxHeapify(int A[],int i)//使i为根的子树成为大顶堆 { int l=2*i;//左子树 int r=2*i+1;//右子树 int largest; if (l<=heapsize && A[l-1]>A[i-1]) {//树的下标从1开始,数组下标从0开始,所以取元素的时候-1 largest=l;//左子树比跟大,左子树标记为largest }else { largest=i;//否则默认根为largest } if (r<=heapsize && A[r-1]>A[largest-1]) { largest=r;//在左根右中,右最大,标记为largest } if (largest!=i) {//根与左右子树中较大元素交换 int tmp=A[i-1]; A[i-1]=A[largest-1]; A[largest-1]=tmp; maxHeapify(A, largest);//再递归调整largest为根的子树 } } public void buildMaxHeap(int A[])//构建大顶堆 { for(int i=A.length/2; i>0 ; i--)//从size/2下标开始往根方向调整,因为后面的都是叶子结点,没有子树 { maxHeapify(A, i); } } public void heapSort(int A[]) {//将根与最后元素交换,然后heapsize-1 heapsize=A.length; buildMaxHeap(A); for(int i=A.length;i>1;i--) { A[0]=A[0]^A[i-1]; A[i-1]=A[0]^A[i-1]; A[0]=A[0]^A[i-1]; heapsize--; maxHeapify(A, 1);//将剩下的继续调整 } } public int getHeapsize() { return heapsize; } public void setHeapsize(int heapsize) { this.heapsize = heapsize; } public static void main(String[] args) { int A[]={20,9,30,15,1,12,0,-1,100,20}; Heap h = new Heap(); h.heapSort(A); for (int i : A) { System.out.println(i); } } }
优先队列代码,其中使用到堆
package chap6; public class PriorityQueue { private static Heap h=new Heap(); public int heapMaximum(int A[]) { return A[0]; } public int heapExtractMax(int A[]) { if(h.getHeapsize()<1) { System.out.println("堆溢出!"); } int max=A[0]; A[0]=A[h.getHeapsize()-1]; h.setHeapsize(h.getHeapsize()-1); h.maxHeapify(A, 1); return max; } public void heapIncreaseKey(int A[],int i,int key) { if (key<A[i-1]) { System.out.println("new key is smaller than current key!"); } A[i-1]=key; while (i>1 && A[i/2-1]<A[i-1]) {//与父节点相比,不断上移,使其满足大顶堆性质 A[i-1]=A[i/2-1]^A[i-1]; A[i/2-1]=A[i/2-1]^A[i-1]; A[i-1]=A[i/2-1]^A[i-1]; i=i/2;//i往上移动 } } public void maxHeapInsert(int A[],int key) { h.setHeapsize(h.getHeapsize()+1); heapIncreaseKey(A, h.getHeapsize(), key); } public static void main(String[] args) { int A[]=new int[100]; h.setHeapsize(0); PriorityQueue p=new PriorityQueue(); p.maxHeapInsert(A, 10); p.maxHeapInsert(A, 20); p.maxHeapInsert(A, 21); p.maxHeapInsert(A, 2); p.maxHeapInsert(A, 18); System.out.println(p.heapMaximum(A)); System.out.println(p.heapExtractMax(A)); System.out.println(p.heapMaximum(A)); p.heapIncreaseKey(A, 5, 22); p.maxHeapInsert(A, 180); System.out.println(p.heapMaximum(A)); } }