Reputation: 158
What kind of math do you use to traverse the 4-heap when using an array to store all the elements? Specifically, how do you find the index of a parent node to a specific leaf?
Let's say I have the following array:
0|1|2|3|4|5|6|7|8|9|10|... etc.
with the heap then constructed from that with 1 being the root, 2..5 its children, 6..9 2's children etc.
What exactly is the math i need if I need to find (for example) the parent of 6?
Upvotes: 1
Views: 2690
Reputation: 881563
To find the parent of any child (other than 1, which has no parent):
parent = int((child + 2) / 4)
To find the first and last child of a parent:
child_first = parent * 4 - 2
child_last = parent * 4 + 1
You can see this in operation since, at each level, you add four times as many elements as you did in the previous level:
1 ( 1)
2 thru 5 ( 4)
6 thru 21 ( 16)
22 thru 85 ( 64)
86 thru 341 ( 256)
342 thru 1365 (1024)
Level 1:
1 -> 2 3 4 5
Level 2:
2 -> 6 7 8 9
3 -> 10 11 12 13
4 -> 14 15 16 17
5 -> 18 19 20 21
Level 3:
6 -> 22 23 24 25
7 -> 26 27 28 29
8 -> 30 31 32 33
9 -> 34 35 36 37
10 -> 38 39 40 41
11 -> 42 43 44 45
12 -> 46 47 48 49
13 -> 50 51 52 53
14 -> 54 55 56 57
15 -> 58 59 60 61
16 -> 62 63 64 65
17 -> 66 67 68 69
18 -> 70 71 72 73
19 -> 74 75 76 77
20 -> 78 79 80 81
21 -> 82 83 84 85
Level 4:
22 -> 86 87 88 89
23 -> 90 91 92 93
24 -> 94 95 96 97
25 -> 98 99 100 101
: : : :
82 -> 326 327 328 329
83 -> 330 331 332 333
84 -> 334 335 336 337
85 -> 338 339 340 341
Examples are:
parent of 342 = int(344/4) = 86 (same for 343,344,345).
parent of 346 = int(348/4) = 87 (same for 347,348,349).
first child of 21 = 21 * 4 - 2 = 82
last child of 21 = 21 * 4 + 1 = 85
Upvotes: 1
Reputation: 33593
First a simple observation. Root is at 1, so all children begin at 2. Before index i there are i-1 vertices (remember, index 0 is not a vertex!) in the heap, each has 4 children exactly. So ith children will be at 2+4*(i-1) to 2+4*i-1 for example, 1's children are 2+4*0=2 to 2+4*0+3=5.
def son_(i):
return range(2+4*(i-1),2+4*i)
for i in range(1,10): print i,son_(i)
output
1 [2, 3, 4, 5]
2 [6, 7, 8, 9]
3 [10, 11, 12, 13]
4 [14, 15, 16, 17]
5 [18, 19, 20, 21]
6 [22, 23, 24, 25]
7 [26, 27, 28, 29]
8 [30, 31, 32, 33]
9 [34, 35, 36, 37]
No holes, see.
If first_son(i)=2+4i and last_son(i)=2+4i+3=4(i+1)+1, we have that father(n)=floor((n-2)/4)+1. (the +1 is to make the array to start at 1)
Let's test that:
def father_(n):
return (n-2)/4+1
for i in range(2,20): print i,father_(i)
Output:
2 1
3 1
4 1
5 1
6 2
7 2
8 2
9 2
10 3
11 3
12 3
13 3
14 4
15 4
16 4
17 4
18 5
19 5
Upvotes: 3
Reputation: 20621
You need integer division and multiplication.
For example, the parent of 6 is 1+((6-1)/4) = 2
.
The parent of 5 is 1+((5-1)/4) = 2
.
The parent of 10 is 1+((10-1)/4) = 3
, etc.
2's children are 2+4*(2-1)..(2+4*(3-1))-1 = 6..9
.
Upvotes: 0