tree/build-heap
建堆
- 类型
- 大顶堆,形状是完全二叉树
- 要守的规矩
- 只管父亲不小于孩子,左右没有意义
- 时间
- O(n)
- 空间
- O(1)
- 结束时的高度
- log2 n
- 每个节点多存
- 无
从已经立着的树开始。同样的堆一个一个插要 n log n,这边只要 n
选一种语言就能看到代码
def heapify(a, end, root): biggest = root left = 2 * root + 1 right = 2 * root + 2 if left < end and a[left] > a[biggest]: biggest = left if right < end and a[right] > a[biggest]: biggest = right if biggest != root: a[root], a[biggest] = a[biggest], a[root] heapify(a, end, biggest) def build_heap(a): for root in range(len(a) // 2 - 1, -1, -1): heapify(a, len(a), root)
function heapify(a, end, root) { let biggest = root; const left = 2 * root + 1; const right = 2 * root + 2; if (left < end && a[left] > a[biggest]) biggest = left; if (right < end && a[right] > a[biggest]) biggest = right; if (biggest === root) return; [a[root], a[biggest]] = [a[biggest], a[root]]; heapify(a, end, biggest); } function buildHeap(a) { for (let root = (a.length >> 1) - 1; root >= 0; root--) { heapify(a, a.length, root); } }
static void heapify(int a[], int end, int root) { int biggest = root; int left = 2 * root + 1; int right = 2 * root + 2; if (left < end && a[left] > a[biggest]) biggest = left; if (right < end && a[right] > a[biggest]) biggest = right; if (biggest == root) return; int t = a[root]; a[root] = a[biggest]; a[biggest] = t; heapify(a, end, biggest); } void build_heap(int a[], int n) { for (int root = n / 2 - 1; root >= 0; root--) heapify(a, n, root); }
void heapify(std::vector<int>& a, int end, int root) { int biggest = root; int left = 2 * root + 1; int right = 2 * root + 2; if (left < end && a[left] > a[biggest]) biggest = left; if (right < end && a[right] > a[biggest]) biggest = right; if (biggest == root) return; std::swap(a[root], a[biggest]); heapify(a, end, biggest); } void build_heap(std::vector<int>& a) { int n = static_cast<int>(a.size()); for (int root = n / 2 - 1; root >= 0; root--) heapify(a, n, root); }
static void Heapify(int[] a, int end, int root) { int biggest = root; int left = 2 * root + 1; int right = 2 * root + 2; if (left < end && a[left] > a[biggest]) biggest = left; if (right < end && a[right] > a[biggest]) biggest = right; if (biggest == root) return; (a[root], a[biggest]) = (a[biggest], a[root]); Heapify(a, end, biggest); } static void BuildHeap(int[] a) { for (int root = a.Length / 2 - 1; root >= 0; root--) { Heapify(a, a.Length, root); } }
static void heapify(int[] a, int end, int root) { int biggest = root; int left = 2 * root + 1; int right = 2 * root + 2; if (left < end && a[left] > a[biggest]) biggest = left; if (right < end && a[right] > a[biggest]) biggest = right; if (biggest == root) return; int t = a[root]; a[root] = a[biggest]; a[biggest] = t; heapify(a, end, biggest); } static void buildHeap(int[] a) { for (int root = a.length / 2 - 1; root >= 0; root--) { heapify(a, a.length, root); } }