Java实现堆排序

public class HeapSort {

public static void HeapAdjust(int[] num, int s, int m){
	int temp = num[s];
	for(int i=2*s;i<=m;i*=2){
		if(i<m&&LT(num,i,i+1))
			i++;
		if(!(temp<num[i]))
			break;
		num[s] = num[i];
		s = i;
	}
	num[s] = temp;
}
public static boolean LT(int[] num, int i, int j){
	if(j>=num.length)
		return false;
	else
		return num[i]<num[j];
}
public static void heapSort(int[] num){
	//构建大顶堆
	for(int i=(num.length/2-1);i>=0;i--)
			HeapAdjust(num, i, num.length-1);
	//取最顶元素 然后重新构建
	for(int i=num.length-1;i>0;i--){
		int temp = num[0];
		num[0] = num[i];
		num[i] = temp;
		HeapAdjust(num, 0, i-1);
	}

		
}
public static void main(String[] args) {
	int [] list = {2,3,1,4,6,5};
	heapSort(list);
	for(int num:list){
		System.out.print(num+" ");
	}

}

}

posted @ 2018-05-07 22:08  Loading~  阅读(190)  评论(0编辑  收藏  举报