Sorting Arrays
Arthur Corliss
corliss at odinicfoundation.org
Tue Sep 28 11:43:13 CDT 1999
On Tue, 28 Sep 1999, Kevin J Creason wrote:
> Here's what I'm doing, and I'm sure I am doing it backwards to
> some degree so please set me straight. I've got a directory
> where I create empty files that are the candidates' names in
> an online election. As each district places their total of
> votes they are appended to the candidates file with district
> name and votes.
> So my "top" array is the canidates names, another toplevel
> array is created that is the total votes for that candidates:
> @canlist @tvote
>
> But each candidate file is opened and that information
> (district # and votes) is dumped into two other arrays:
> @district{$c,$vc} and $subvote{$c,$vc}
> The scalar 'c' matches the current canlist/tvote and 'vc'
> increments for the each district/vote entry.
>
> Subvotes are added together to create one of the array entries
> $tvote. I hold on to the district for later statistics by
> district.
>
> Here is my dilemma: I want to sort my @canlist and tvote by
> tvote, so that highest vote getters are listed on top instead
> of alphabetically. I'm sure there is a way, I just haven't
> found it yet, but I also have to keep the other arrays in
> sync.
> Any ideas? If I have to completely recode that _may_ not be a
> bad thing... :)
> TIA
> Kevin
One way to do that (albeit by brute force) is a simple bubble sort. Instead
of two arrays, though, I might recommend a hash of candidate => votes, and an
array whose indexed order will be the sorted order. Perhaps:
@by_votes = (keys %candidate);
for ($m = 0; $m < scalar @by_votes; $m++) {
for ($i = $m + 1; $i < scalar @by_votes; $i++) {
@by_votes[$m,$i] = @by_votes[$i,$m] if
($candidate{$by_votes[$m]} < $candidate{$by_votes[$i]});
}
}
--Arthur Corliss
Bolverk's Lair -- http://www.odinicfoundation.org/arthur/
"Live Free or Die, the Only Way to Live" -- NH State Motto
=================================================
Mailing list info: If at any time you wish to (un|re)subscribe to
the list send the request to majordomo at hfb.pm.org. All requests
should be in the body, and look like such
subscribe anchorage-pm-list
unsubscribe anchorage-pm-list
More information about the Anchorage-pm
mailing list