In addition to the suggestions already given, you could sort your array, and
then look at the middle and cut it in half (potentially several times). I
forget the name for this technique, though...

For example, you have 1000 elements, sorted. You compare your number to the
500th element. If it's higher, you throw away the first 500 elements. Then
you compare your number to the 250th element, decide which half your number
belongs in, and throw away the other half. If you just do that twice, you've
reduced the amount of data you have to look through by a factor of four.

Paul


3:20pm, Ramprasad wrote:

> Rafaqat Ali Chaudhry wrote:
> > Dear all,
> >
> > I've a function which searches a given number from an array and returns
> > the result.
> >
> > Function:
> >
> > 1.  sub checkNumber($)
> > 2.  {
> > 3.          my ($l_number) =  @_;
> > 4.          my $l_status;
> > 5.          my @matches= grep { /$l_number/ } @numbers;
> > 6.          if  (@matches) {
> > 7.                  $l_status="TRUE";
> > 8.          }
> > 9.          else {
> > 10.                 $l_status="FALSE";
> > 11.         }
> > 12.         return $l_status;
> > 13. }
> >
> > The Way I call it:
> >
> > 1.  $check=checkNumber($num1);
> >
> > The array has at least 20K elements. This piece of code is taking up
> > almost 100% of the CUP cycles. Would somebody please suggest some
> > alternative solution.
> >
> > Thanks in Advance
> >
> > Rafaqat Ali Chaudhary
>
>
> You can improve the code largely by just returning immediately as you
> get a match
>
> ( dont use grep when you dont need it )
>
>
> sub check  {
> my ($l_number) =  @_
> foreach ( @numbers) {
>    return 'TRUE' if($_ == $l_number);
> }
> return 'FALSE';
> }
>
> So every false condition would have gone thru all elements but every
> true condition will return immediately
>
>
> Besides if you are doing this check a lot many times in your program It
> may be better to create a hash array. Hash arrays are implemented real
> good in perl
> then you can use
>
> In the main script put
>
> my %hash = ();
> @[EMAIL PROTECTED]();
>
> so  you can check directly
>
> if(exists($hash{$l_number})) {
>
>     ...... # this is TRUE ....
>
> } else {
>
>    ........ # this is FALSE ....
>
> }
>
>
>
> The Hash method will take more memory but will be much quicker
>
>
>
> Thanks
> Ram
>
>
>

---------------------------------------------------------------------
On the side of the software box, in the "System Requirements" section,
it said "Requires Windows 95 or better".  So I installed Linux.
---------------------------------------------------------------------

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to