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


In reply to Re: Sorting an array containing version numbers by talexb
in thread Sorting an array containing version numbers by appu_rajiv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.