【JAVA算法】经典排序算法 --堆排序HeapSort

public class Main {
	static int heapLen;//堆的大小
	static int[] heapList= {0,5,4,7,1,3};//堆数组的第一个位置不放元素;
	//judge函数,找出父节点与两个子节点的中最大的,并返回最大元素的下标
	public static int judge(int pos){
		if(2*pos>heapLen){
			return pos;
		}else if(2*pos+1>heapLen){
			if(heapList[pos]<heapList[2*pos]){
				return 2*pos;
			}else{
				return pos;
			}
		}else{
			if((heapList[pos]>=heapList[2*pos])&&(heapList[pos]>=heapList[2*pos+1])){
				return pos;
			}else{
				if(heapList[2*pos]>=heapList[2*pos+1]){
					return 2*pos;
				}else{
					return 2*pos+1;
				}
			}
		}
	}
	//输入一个下标,从这个下标开始调整堆。
	public static void adjustHeap(int pos){
		while(judge(pos)!=pos){
			int temp;
			int p =judge(pos);
			temp = heapList[pos];
			heapList[pos] = heapList[p];
			heapList[p] = temp;
			pos = judge(pos);
		}
	}
	//创建堆
	public static void creatHeap(){
		for(int i=heapLen/2;i>=1;i--){
			adjustHeap(i);
		}
	}
	//删除堆首元素
	public static void deleteHeap(){
		//交换首尾元素
		int temp;
		temp = heapList[1];
		heapList[1] = heapList[heapLen];
		heapList[heapLen] = temp;
		heapLen--;
		adjustHeap(1);
	}
	//输出堆
	public static void printList(){
		for (int i=1;i<=heapList.length-1;i++){
			System.out.print(heapList[i]+" ");
		}
		System.out.println();
	}
	public static void main(String[] args){
		heapLen = heapList.length-1;
		creatHeap();
		for (int i=1;i<heapList.length-1;i++){
			deleteHeap();
		}
		printList();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值