一.堆的介绍
动态效果图
package data; import java.util.Arrays; import java.util.Random; /** * 堆排序 * @author JYC506 * */ public class HeapSort { public static void sort(int[] arr){ Heap heap=new Heap(arr.length); for(int i=0;i<arr.length;i++){ heap.insert(arr[i]); } for(int i=arr.length-1;i>-1;i--){ arr[i]=heap.remove(); } } public static void main(String[] args) { /*创建堆*/ int num=10; Heap heap=new Heap(num); int[] arr=new int[num]; Random ran=new Random(); for(int i=0;i<num;i++){ int data= ran.nextInt(num); heap.insert(data); arr[i]=data; } System.out.println(heap); for(int i=0;i<num;i++){ System.out.println("移除出来的数据:"+heap.remove()); } System.out.println("移除完所有数据后的堆里面的数组的情况:"+heap); /*直接用堆排序*/ System.out.println("堆排序前:"+Arrays.toString(arr)); HeapSort.sort(arr); System.out.println("堆排序后:"+Arrays.toString(arr)); } } /** * 堆 * */ class Heap { /*当前存储空间*/ private int[] arr; /*最大的范围*/ private int maxSize; /*现在的大小*/ private int currentSize; public Heap(int maxSize) { this.maxSize = maxSize; this.currentSize = 0; this.arr = new int[maxSize]; } public int remove() { int data = arr[0]; /*移除根并且把最后一个节点移动到跟的位置,大小减一*/ this.arr[0] = arr[--currentSize]; /*渗透*/ this.trickleDown(0); /*删除的部分使用同一数组*/ arr[this.currentSize]=data; return data; } public boolean insert(int data) { if (currentSize == maxSize) { return false; } arr[currentSize] = data; /*冒泡*/ this.trickleUp(currentSize++); return true; } /*插入数据时冒泡*/ private void trickleUp(int index) { int parent = (index - 1) / 2; int buttom = arr[index]; /*当有父节点时*/ while (index > 0 && arr[parent] < buttom) { arr[index] = arr[parent]; index=parent; parent = (parent - 1) / 2; } arr[index] = buttom; } /*删除数据时候渗透*/ private void trickleDown(int index) { int largerChild; int top = arr[index]; /*当有子节点*/ while (index < this.currentSize / 2) { int leftChild = 2 * index + 1; int rightChild = leftChild + 1; if (rightChild < currentSize && arr[leftChild] < arr[rightChild]) { largerChild = rightChild; } else { largerChild = leftChild; } if (top > arr[largerChild]) { break; } arr[index] = arr[largerChild]; index = largerChild; } arr[index] = top; } @Override public String toString() { return "Heap [arr=" + Arrays.toString(arr) + "]"; } public int[] getArr() { return arr; } }
原文地址:http://blog.csdn.net/h348592532/article/details/45508715