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());
}
}
}
}
堆排序
最新推荐文章于 2023-09-21 13:21:58 发布