最近做题目饱受打击,愈发觉得打好基础的重要性,于是乎,决心把基本的排序算法还有数组操作一一实现,目的在于
一方面能够得到对JAVA基础的巩固,另一面在实现的过程中发现不足。
今天所实现的堆排序(最大堆)算法,最小堆大同小异。然后基于最大堆实现最大优先队列,最大优先队列可应用于作
业调度,比如可将作业长度作为关键字值,实现最长作业优先;或者将作业优先权值作为关键字值,实现高优先权作业优先
执行等等。
最大堆排序算法结构如下图:
1 //:ThinkingInJava/com.mindview.fundamental/MaxHeap.java 2 package com.mindview.fundamental; 3 /** 4 * 5 * @Time 2014-6-17 6 * @Descri MaxHeap.java 最大堆排序实现算法 7 * parent (i-1)/2 8 * left 2*i+1 9 * right 2*i+2 10 * @author pattywgm 11 * 12 */ 13 public class MaxHeap { 14 int a[]; 15 int a_heapsize; 16 //接受数组 17 public MaxHeap(int a[]) { 18 this.a=a; 19 a_heapsize=a.length; 20 } 21 22 //堆排序 23 public void heapSort(){ 24 buildMaxHeap(); 25 for(int i=a.length-1;i>0;i--){ 26 //从大到小输出,实际数组顺序输出为从小到大 27 // System.out.print(a[0]+" "); 28 exchange(0, i); 29 a_heapsize=a_heapsize-1; 30 maxHeapIFY(0);//from top to bottom 31 } 32 } 33 34 //创建堆 35 public void buildMaxHeap(){ 36 //a[(a.length-1)/2] to a[0] is not leaf 37 for(int i=(a.length/2-1);i>=0;i--){ 38 maxHeapIFY(i); 39 } 40 } 41 //调整堆,以使其符合最大堆性质 42 public void maxHeapIFY( int i) { 43 int aLeft=2*i+1;//leftChild 44 int aRight=2*i+2;//rightChild 45 int largest; 46 if(aLeft<a_heapsize && a[aLeft]>a[i]) 47 largest=aLeft; 48 else 49 largest=i; 50 if(aRight<a_heapsize && a[aRight]>a[largest]) 51 largest=aRight; 52 if(largest!=i){ 53 exchange(i,largest); 54 //子树可能违反最大堆性质,继续调整 55 maxHeapIFY(largest); 56 } 57 58 59 } 60 //exchange A[i] with A[largest] 61 public void exchange(int i, int largest) { 62 int temp=a[i]; 63 a[i]=a[largest]; 64 a[largest]=temp; 65 66 } 67 } 68 69 ///:~