Think about Loose Coupling | |
PerlMonks |
Re^6: Re-orderable keyed access structure?by BrowserUk (Patriarch) |
on Aug 15, 2004 at 04:24 UTC ( [id://383050]=note: print w/replies, xml ) | Need Help?? |
Sorry, but I'm having trouble picturing how this works? A binary tree in an array. Highest value is always root (element 0?). How do I locate the second highest item? If it's always element 1, then you talking about a sorted array, that resorts itself as you add items to it or change the weight any of the items. The array elements contain the weights, where does the payload go? So the array becomes an AoA? Raising an items weight to the top means assigning that item a weight higher than the weight in $array[0][0]--easy enough. But then, the process of re-sorting the list is to move the newly highest weighted item to position 0. This is done by comparing this items weight with that of the item above it and if its higher (which it always will be), swap the two items and repeat with the next highest item. Keep repeating until it has found it's way to the top. This is a bubble sort. If the previously lowest item in the heap/array gets modified, then it's weight gets set to the highest value +1 (eg. $array[ 0 ][ 0 ] ). The heap algorithm then swaps it with every item in the heap/array, one at a time, until it reaches the top. Given that I already know that I am moving the item to the top of the list, the splice operation is vastly more efficient. Once I am going to do that, there is no point in embedding the weight within each element, because it is always, directly related to the elements position in the array. Ie. The elements position is it's weight. Back to square one. If I have this wrong (and I am pretty sure that I don't) then please illustrate a 5 element weighted heap and the steps required to raise the middle element to top (or bottom).
In Section
Seekers of Perl Wisdom
|
|