Paul Archer wrote: > > 3:20pm, Ramprasad wrote: > > > > Rafaqat Ali Chaudhry wrote: > > > > > > 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. > > > > 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 > > 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...
Binary search. > 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. If the array is already sorted then using a binary search will in most cases be faster than using a linear search however the overhead of sorting the array first might negate that advantage. If you want to be sure which is faster you should bechmark both methods. John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]