• 堆排序


    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));
    
    	}
    
    }
    堆排序代码

      

  • 相关阅读:
    例5-6
    例5-5
    例5-4
    例4-5
    例4-4
    例4-3
    例4-2
    例3-11
    例3-10
    例3-9
  • 原文地址:https://www.cnblogs.com/waxili/p/3129874.html
Copyright © 2020-2023  润新知