堆排序

package com.sort;

public class HeapSort {
	public static void main(String[] args) {
		HeapSort heapSortObj = new HeapSort();
		int[] a = new int[] { 4, 3, 6, 5, 4, 3, 2, 1 };
		MinHeap maxHeap = heapSortObj.new MinHeap(a, a.length);
		maxHeap.buildHeap();
		maxHeap.heapSortAndPrint();
	}

	class MinHeap {
		private int[] heap;
		private int size = 0;

		MinHeap(int[] heap, int length) {
			this.heap = heap;
			this.size = length;
		}

		public int parent(int pos) {
			return (pos - 1) / 2;
		}

		public int leftchild(int pos) {
			return 2 * pos + 1;
		}

		public int rightchild(int pos) {
			return 2 * pos + 2;
		}

		public boolean isLeaf(int pos) {
			return (pos < size) && (pos >= size / 2);
		}

		public void buildHeap() {
			for (int i = size / 2 - 1; i >= 0; i--) {
				siftdown(i);
			}
		}

		public void siftdown(int pos) {//向下拉的过程
			while (!isLeaf(pos)) {
				int left = leftchild(pos);
				if (left < size - 1 && heap[left] > heap[left + 1]) {//加left<size-1来剔除掉没有右兄弟结点的情况
					left++;
				}
				if (heap[pos] <= heap[left])//满足最小堆序直接跳出
					return;//由于buildHeap向下拉的过程是从最后一个分支节点不断往根节点靠近。所以向下拉时下层堆序已经形成,如果heap[pos] <= heap[left]则可直接退出。
				swap(heap, pos, left);
				pos = left;
			}
		}

		public int remove() {
			swap(heap, 0, --size);
			if (0 != size)
				siftdown(0);
			return heap[size];
		}

		public void swap(int[] a, int j, int i) {
			int temp = a[j];
			a[j] = a[i];
			a[i] = temp;
		}

		public void heapSortAndPrint() {
			while (size > 0) {
				System.out.println(remove());
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值