堆排序(java实现)
public class Test04 { static int a[] = {9,8,7,6,5,4,3,2,1,11,12,10,19,18,17,16}; public static void main(String[] args) { init(); int i,k; for(i = 0;i< a.length -1;i++){ k = a[0]; a[0] = a[a.length-1-i]; a[a.length-1-i] = k; sort(0,a.length-i-1); } for(int b :a){ System.out.print(b+" "); } } public static void init(){ int i = (a.length-1)/2; for(;i >=0;i--){ sort(i,a.length); } } public static void sort(int i,int length){ int k = i; if(2*i+1 < length && a[k] < a[2*i+1]){ k = 2*i+1; } if(2*i+2 < length && a[k] < a[2*i+2] ){ k = 2*i+2; } if(k != i){ a[i] = a[k]+a[i]; a[k] = a[i]-a[k]; a[i] = a[i]-a[k]; sort(k,length); } } }