排序系列之堆排序

堆积排序(Heapsort)是指利用堆积树(堆)这种资料结构所设计的一种排序算法,可以利用数组的特点快速定位指定索引的元素。

public class HeapSort {
	public final static void heapSort(int a[]){
		new MiniPriorityQueue(a);
	}
	private static class MiniPriorityQueue {
		private final int queue[];
		private int size;

		public MiniPriorityQueue(int a[]) {
			this.size = a.length;
			this.queue = a;
			heapify();
			while(this.isNotEmpty()){
				this.pop();
			}
		}
		private void heapify() {
			for (int i = (this.size >>> 1) - 1; i >= 0; i--)
				siftDown(i, this.queue[i]);
		}

		private void siftDown(int index, int value) {
			int i = this.size >>> 1;
			while (index < i) {
				int j = (index << 1) + 1;
				int temp = this.queue[j];
				int k = j + 1;
				if ((k < this.size) && (this.queue[j] > this.queue[k])) {
					temp = this.queue[(j = k)];
				}
				if (temp > value)
					break;
				this.queue[index] = temp;
				index = j;
			}
			this.queue[index] = value;
			
		}
		public void pop(){
			int result = this.queue[0];
		    int value = this.queue[--this.size];
		    siftDown(0, value);
		    this.queue[this.size]=result;
		}
		public boolean isNotEmpty(){
			return this.size != 0;
		}
	}
	public static void main(String[] args) {
		int[] a= new int[]{5,3,7,8,2,6,1,4};
		heapSort(a);
		System.out.println(Arrays.toString(a));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值