1. 程式人生 > >堆排序(java)

堆排序(java)

//主要思想:經過初始調整之後,對於每一次取數(將頂端元素與最後一個元素交換)之後都要對堆進行調整

public class HeapSort{
	public static void main(String[]args){
		int []A={1,2,10,0,-3,7,6,20,11};
		heapsort(A);
	}
	public static void heapsort(int []A){
		int len=A.length;
		adjustheap(A,0,len-1);
		for(int j=0;j<len;j++){
			System.out.print(A[j]+" ");
		}
		System.out.println();
		for(int i=0;i<len;i++){
			System.out.print(deleteTop(A,0,len-i-1)+" ");
			adjustheap(A,0,len-i-2);
		}

	}
	public static void adjustheap(int []A,int low,int high){
		int t;
		for(int i=high/2;i>=0;i--){
			if(2*i+1<=high){
				if(A[2*i+1]<A[i]){
					t=A[2*i+1];
					A[2*i+1]=A[i];
					A[i]=t;
				}
			}
			if(2*i+2<=high){
				if(A[2*i+2]<A[i]){
					t=A[2*i+2];
					A[2*i+2]=A[i];
					A[i]=t;
				}
			}
		}
	}
	public static int deleteTop(int []A,int low,int high){
		int t=A[0];
		A[0]=A[high];
		A[high]=t;
		return t;

	}

}