in reply to Sorting an array containing version numbers

I have put together the following solution ..

#!/usr/bin/perl -w # # Sort version numbers use strict; use warnings; { my @versions = qw/2.4.74 3.2.5 1.14.56 1.45.2 3.14.75/; print "Original version string:\n" . join( "\n", @versions ) . "\n +"; print "Sorted version strings:\n" . join( "\n", sort compareVersionStrings @versions ) . "\n"; } # Compare two version strings. # # Among other assumptions, this code assumes that the version strings + have the # same number of elements in them. Thus, comparing 3 against 2 will w +ork; as # will 3.1 against 2.7 and 3.1.4 against 2.7.18. Comparing 2.0 agains +t 4 will # fail, as will 2.0 against 4.5.6. sub compareVersionStrings { my ( @a, @b ); my @left = split( /\./, $a ); my @right = split( /\./, $b ); return ( $left[0] <=> $right[0] || $left[1] <=> $right[1] || $left[2] <=> $right[2] ); }
It seems to work, although there are some limitations, as I've explained in the comment.

However, as others have already pointed out, this sounds like premature optimization.

You haven't explained why an optimized method is required. Are you expecting to have to do this thousands of times a second?

If you're sincere in your request to speed it up, you'll need to hash the version numbers into something that's very easily sorted -- a trivial solution would be to multiply major by 1,000,000, minor by 1,000 and add the three values together, giving you a single number that should sort correctly.

Alex / talexb / Toronto

Team website: Forex Chart Monkey, Forex Technical Analysis and Pickpocket Prevention

"Groklaw is the open-source mentality applied to legal research" ~ Linus Torvalds