P is for Practical | |
PerlMonks |
Re: What makes an array sorted and a hash unsorted?by shmem (Chancellor) |
on Jun 02, 2009 at 09:44 UTC ( [id://767527]=note: print w/replies, xml ) | Need Help?? |
What is 'sorted'? (unsorted) data is sorted after sorting. An array is sorted because it can return its values in order of ascending keys (indexes). No. An array is sorted when their values are sorted, by whatever order you impose on them. I consider the following
as an unsorted array. Iterating over an array via ascending indexes or, in a destructive way, via shift or pop is the natural way to access all values sequentially, just like each does for hashes. Arrays are a defined sequence of scalars on which you can impose any order in a stable way, e.g. by sorting the values
meaning that after that operation the sequential iteration over the array whith ascending or descending keys reflects the order which you impose on the data. That's not possible with hashes. You can't impose a different order of key/value tupels on a hash to change the order in which each returns those tupels. That's meant by 'hashes are not sortable'. If you fill a hash sequentially which tupels, retrieveing those via each doesn't necessarily reflect the initial filling sequence. That's meant by 'hashes are unordered' (or unsorted).
This may change the order in which each returns tupels iterating over the hash, but not in a predictable way, and certainly their sequence doesn't reflect the sorting. But you can do that with arrays. That's what makes arrays sorted (if you sort them) but hashes unsorted: you can't impose a different stable order in which tupels are returned. Sorting applies to a sequence. If we look at hashes as a collection of tupels, we note that we can't influence the ordering of tupels retrieving those as a sequence. But that's due to the fact that arrays are sequences, and hashes are not: "associative array" for perl hashes is a misnomer ;-)
In Section
Meditations
|
|