大根堆
public class Heap {int[] nums = new int[10];int heapSize = 0;public static void main(String[] args) {Heap heap = new Heap();heap.add(4);heap.add(1);heap.add(3);heap.add(6);heap.add(2);heap.add(9);heap.add(4);// 9int remove1 = heap.remove();// 6int remove2 = heap.remove();// 4int remove3 = heap.remove();// 4int remove4 = heap.remove();// 3int remove5 = heap.remove();heap.add(10);// 10int remove6 = heap.remove();System.out.println();}private void add(int num){if (heapSize == nums.length){synchronized (nums){int[] numsNew = new int[nums.length + 10];System.arraycopy(nums,0,numsNew,0,nums.length);nums = numsNew;}}nums[heapSize] = num;up(heapSize);heapSize++;}private int remove(){int num = nums[0];nums[0] = nums[--heapSize];down(0);return num;}/*** index位置和父节点比较,大于父节点就交换*/private void up(int index){int parentIndex = (index-1)/2;while (nums[index] > nums[parentIndex]){swap(nums,index,parentIndex);index = parentIndex;parentIndex = (index-1)/2;}}/*** index和子节点比较,子节点先选出最大的,然后和index比较,index小的话则交换*/private void down(int index){int leftChildIndex = 2 * index + 1;while (leftChildIndex < heapSize){int maxChildIndex= leftChildIndex;if (leftChildIndex + 1 < heapSize && nums[leftChildIndex] < nums[leftChildIndex+1]){maxChildIndex++;}if (nums[index] >= nums[maxChildIndex]){return;}swap(nums,index,maxChildIndex);index = maxChildIndex;leftChildIndex = 2 * index + 1;}}private void swap(int[] nums, int i, int j){if (i == j) {return;}int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}}
堆排序
从后往前做下调动作,这样能减少调整次数。调整完后变成一个大根堆
然后堆顶元素和最后元素做交换,堆空间减少1,然后让堆顶元素下沉调整。
private void sort(int[] nums){this.nums = nums;heapSize = nums.length;//构建大根堆for (int i = nums.length-1; i >= 0; i--) {down(i);}//堆顶是最大值,直接放在最后,然后减少对size,在新size上对目前堆顶的元素进行调整while (heapSize > 0){swap(nums,0,--heapSize);down(0);}}
