为什么不使用堆数组的零元素? [英] Why is element zero of a heap array not used?

查看:75
本文介绍了为什么不使用堆数组的零元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我对具有任意值的堆开始的粗略概图

Here's my rough sketch of the beginning of a heap with arbitrary values

 0   1    2    3    4    5    6    7    8    9   ...
[-] [10] [14] [15] [22] [21] [24] [23] [44] [30] ...

为什么必须将array [0]中的元素始终设置为null?
还是为什么我们不应该使用它?

Why must the element in array[0] always be set to null?
Or why is it that we are not supposed to use it?

推荐答案

有几种方法可以将二进制堆表示为数组.

There are several ways to represent a binary heap as an array.

有一种方法可以使用零元素.还有一种方法,其中不使用元素零:

There is a way whereby element zero is used; there is also a way whereby element zero is not used:

  1. root是元素0;元素n的子元素是元素2n+12n+2;
  2. root是元素1;元素n的子元素是元素2n2n+1.
  1. root is element 0; children of element n are elements 2n+1 and 2n+2;
  2. root is element 1; children of element n are elements 2n and 2n+1.

两个都不比另一个更正确".前者更适合使用从零开始的数组的编程语言. a>,而后者更适合使用基于一个数组的语言.

Neither is more "correct" than the other. The former is a better fit for programming languages that use zero-based arrays, whereas the latter is a better fit for languages with one-based arrays.

似乎您遇到了使用第二种方法的实现.由于所讨论的语言Java使用基于零的数组,因此零元素存在但未被使用.

It would appear that you've encountered an implementation that uses the second approach. Since the language in question, Java, uses zero-based arrays, element zero exists but is not being used.

这篇关于为什么不使用堆数组的零元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆