while loop

Hi,

I have written java service for binary search. The execution of while loop in the code is taking more time.

Can anyone tel me the reason please. I have also tried using for loop.

Thanks in advance.

regards,
Monica

Hi Monica:

What’s exactly do your loop? Do you tried with many loops?, you should use to loop WebMethods

Hi,

Loop will iterate over the no of elements.

If search element matches with mid element then return mid position.

If search element lesser than mid then search first half of input elements else search second half.

Hi Monica:

Are you searching in xml file? or a simple array?

hi,

input is an string list…n while loop will loop over this list…

You’re making us guess as to what might be the root cause of the issue with very minimal information. If you can post the FLOW and Java code you’re working with then we’ll have a better chance at determining what’s happening.

hi,

below is my code for binary search…

inputs----input(stringList),value(string)
output-----pos(string)

// pipeline
IDataCursor pipelineCursor = pipeline.getCursor();
String[] input = IDataUtil.getStringArray( pipelineCursor, "input" );
String value = IDataUtil.getString( pipelineCursor, "value" );
pipelineCursor.destroy();
Integer bin[]=new Integer[input.length];
for(int i=0;i<input.length;i++)
{
bin[i]=Integer.parseInt(input[i]);
}
int val=Integer.parseInt(value);
Integer pos=0;
int low=0;
int high=input.length-1;
while (low <= high)
 {
          int middle = (low + high) / 2;
            if (bin[middle] == val)
  { pos=middle; 
  }
            else if (bin[middle] > val)
  { high = middle - 1;
  }
            else
  { low = middle + 1;
  }
}
String p=pos.toString();
// pipeline
IDataCursor pipelineCursor_1 = pipeline.getCursor();
IDataUtil.put( pipelineCursor_1, "pos", p );
pipelineCursor_1.destroy();

Hi Monica,
I think the problem is here in this part.

[COLOR=black][FONT=Verdana]

[/font][/color]

The while loop keeps continuing even after you have determined the output. Once the control reaches this point there happens no change in the values of either low or high and hence the loop would continue indefinitely.

You could try havinga break statement right after pos=middle, that will work.

HTH,
Suren

hi,

Ya if we give break statement after pos=middle it works…

Thanks a lot …:happy:

Regards,
Monica