develooper Front page | perl.beginners | Postings from February 2009

Re: How to speed up two arrays compare.

Thread Previous
Raymond Wan
February 11, 2009 00:16
Re: How to speed up two arrays compare.
Message ID:

Hi Kevin,

kevin liu wrote:
>         I have two arrays(@nwarray0 and @nwarray1) in my program and i want
> to make sure that
> all the elements in @nwarray0 could be found in @nwarray1.

Your problem is a common problem that is not specific to Perl.  A common solution is to place one of the arrays into a hash and then do a pass through the second array.

What you are currently doing is comparing every element in an array of "m" items with every element in an array of "n" items.  So, you are doing "m * n" comparisons.

If you place all of the m items in a hash, then you will only do "n" comparisons....*assuming* that hash retrieval occurs in constant time.  

Rather than write a hash function yourself, you can just use Perl's.  See this for more information:  or just search for "hashes" or "associative arrays".


PS:  No source code...I think you can figure it out from here; good luck!  :)

Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About