堆排序(Java)

/**
 * HeapSort
 * 
 */
public class HeapSort {

	public static void sort(Comparable[] a) {
		int N = a.length-1;
		int i = N/2;
		while(i >= 1) {
			sink(a, i, N);
			i--;
		}
		
		while(N > 1) {
			exch(a, 1, N--);
			sink(a, 1, N);
		}
	}
	
	private static void sink(Comparable[] a, int k, int N) {
		int i = -1;
		while(k*2 < N) {
			if(less(a[k*2], a[k*2+1])) {
				i = k*2 + 1;
			} else {
				i = k*2;
			}
			if(less(a[k], a[i])) {
				exch(a, k ,i);
				k = i;
			} else {
				break;
			}
		}
	}
	
	private static boolean less(Comparable v, Comparable w) {
		return v.compareTo(w) < 0;
	}
	
	private static void exch(Comparable[] a, int i, int j) {
		Comparable tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}
	
	public static void show(Comparable[] a) {
		for(int i=0; i<a.length; i++) {
			System.out.println(a[i]);
		}
	}
}

你可能感兴趣的:(java,堆排序)