用java语言实现升序/降序排序(堆排序)

package cn.bintree;

import java.util.Arrays;

/*
 * create by yike on 2020/10/18
 * 堆排序
 */

public class HeapSortDemo {

	public static void main(String[] args) {
		int[] arry = {5,6,2,3,9,7,1};
		HeapSort heap = new HeapSort();
		heap.setHeap(arry);
		System.out.println(Arrays.toString(heap.ascOrder()));
		int[] arry1 = {8,4,6,32,54,2,51};
		heap.setHeap(arry1);
		System.out.println(Arrays.toString(heap.desOrder()));
	}
}
class HeapSort{
	/**
	 * @len 记录每次循环后,下次数组长度
	 * @heap 接受堆排序的数组
	 * @temp 用于交换元素位置时的辅助指针
	 */
	private int len;
	private int[] heap;
	private int temp;
	public void setHeap(int[] heap) {
		this.heap=heap;
		this.len=heap.length;
	}
	public int[] ascOrder() {//大顶推完成数组升序排序
		while(len>=2) {
			//第一轮
			for(int i=(len/2-1);i>=0 && i<len;i--) {
				ascNode(i);
			}
			heap[0]=heap[len-1];
			heap[len-1]=temp;
			len--;	
		}
		return heap;
	}
	public void ascNode(int n) {//非页子节点的比较和交换过程
		temp=heap[n];
		if((2*n+1)<len && temp<heap[2*n+1]) {
			heap[n]=heap[2*n+1];
			heap[2*n+1]=temp;
			temp=heap[n];
		}
		if((2*n+2)<len && temp<heap[2*n+2]) {
			heap[n]=heap[2*n+2];
			heap[2*n+2]=temp;
			temp=heap[n];
		}
	}
	public int[] desOrder() {//小顶堆完成数组降序排序
		while(len>=2) {
			for(int i=(len/2-1);i>=0 && i<len;i--) {
				desNode(i);
			}
			heap[0]=heap[len-1];
			heap[len-1]=temp;
			len--;	
		}
		return heap;
	}
	public void desNode(int n) {
		temp=heap[n];
		if((2*n+1)<len && temp>heap[2*n+1]) {
			heap[n]=heap[2*n+1];
			heap[2*n+1]=temp;
			temp=heap[n];
		}
		if((2*n+2)<len && temp>heap[2*n+2]) {
			heap[n]=heap[2*n+2];
			heap[2*n+2]=temp;
			temp=heap[n];
		}
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值