堆排序
import java.util.Arrays; public class HeapSort<E extends Comparable<E>> { /** * @param args */ private Object[] queue; private int size = 0; public HeapSort(Object[] queue) { this.size = queue.length; this.queue = queue; } private void heapsort() { Object tmp; while (size != 0) { heapify(); tmp = queue[0]; queue[0] = queue[size - 1]; queue[size - 1] = tmp; size--; } } @SuppressWarnings("unchecked") private void heapify() { for (int i = (size >>> 1) - 1; i >= 0; i--) siftDown(i, (E) queue[i]); } @SuppressWarnings("unchecked") private void siftDown(int k, E x) { int half = size >>> 1; while (k < half) { int child = (k << 1) + 1; Object c = queue[child]; int right = child + 1; if (right < size && ((Comparable<E>) c).compareTo((E) queue[right]) > 0) c = queue[child = right]; if (((Comparable<E>) x).compareTo((E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = x; } public static void main(String[] args) { // TODO Auto-generated method stub Object[] obj = new Object[] { new Float(13), new Float(25.2), new Float(4), new Float(8), new Float(10), new Float(14.63), new Float(3), new Float(0), new Float(47), new Float(15) }; HeapSort<Float> h = new HeapSort<Float>(obj); System.out.println(Arrays.toString(h.queue)); h.heapsort(); System.out.println(Arrays.toString(h.queue)); } }
堆排序代码