数组堆化

今天学习了数组堆化, 堆化启发我们的思维, 百尺竿头更进一步!

理解堆化

说是堆化, 其实就是利用树的性质表示在数组中, 利用下标和书上左右孩子对应关系.

公式

  • 左孩子下标 = 根下标 * 2 + 1
  • 右孩子下标 = 根下标 * 2 + 2

递归

递归 fixHead 函数来解决满足大顶堆或者小顶堆的问题, 说到递归, 我们一般会说递归结束条件, 数组越界或者已经符合条件, 结束递归.

源码

public class Main {
	public static void main(String[] args) {
		int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ,0};
		for (int i = arr.length / 2 - 1; i > -1; i--) {
			fixHead(arr, i, arr.length - 1);
		}
	}

	public static void fixHead(int[] arr, int headIndex, int limitIndex) {
		int leftChildIndex = headIndex * 2 + 1;
		int rightChildIndex = headIndex * 2 + 2;
		if (leftChildIndex > limitIndex || rightChildIndex > limitIndex) {
			return;
		}
		int selectIndex = -1;
		if (arr[leftChildIndex] <= arr[rightChildIndex]
				&& arr[leftChildIndex] < arr[headIndex]) {
			selectIndex = leftChildIndex;
		}
		if (arr[rightChildIndex] <= arr[leftChildIndex]
				&& arr[rightChildIndex] < arr[headIndex]) {
			selectIndex = rightChildIndex;
		}
		if (selectIndex != -1) {
			int tempValue = arr[selectIndex];
			arr[selectIndex] = arr[headIndex];
			arr[headIndex] = tempValue;
			fixHead(arr, selectIndex, limitIndex);
		}
	}
}

结果

输入:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
输出:
[0, 1, 4, 2, 6, 5, 8, 3, 7, 9, 10]
posted @ 2019-09-07 21:21  哈缺氧  阅读(651)  评论(0编辑  收藏  举报