堆积排序(Heapsort)是指利用堆积树(堆)这种资料结构所设计的一种排序算法,可以利用数组的特点快速定位指定索引的元素。
public class HeapSort { public final static void heapSort(int a[]){ new MiniPriorityQueue(a); } private static class MiniPriorityQueue { private final int queue[]; private int size; public MiniPriorityQueue(int a[]) { this.size = a.length; this.queue = a; heapify(); while(this.isNotEmpty()){ this.pop(); } } private void heapify() { for (int i = (this.size >>> 1) - 1; i >= 0; i--) siftDown(i, this.queue[i]); } private void siftDown(int index, int value) { int i = this.size >>> 1; while (index < i) { int j = (index << 1) + 1; int temp = this.queue[j]; int k = j + 1; if ((k < this.size) && (this.queue[j] > this.queue[k])) { temp = this.queue[(j = k)]; } if (temp > value) break; this.queue[index] = temp; index = j; } this.queue[index] = value; } public void pop(){ int result = this.queue[0]; int value = this.queue[--this.size]; siftDown(0, value); this.queue[this.size]=result; } public boolean isNotEmpty(){ return this.size != 0; } } public static void main(String[] args) { int[] a= new int[]{5,3,7,8,2,6,1,4}; heapSort(a); System.out.println(Arrays.toString(a)); } }
09-16
09-16