Home > Back-end >  For help! Could you tell me why sometimes lose the results of this program, sometimes not
For help! Could you tell me why sometimes lose the results of this program, sometimes not

Time:09-30


import java.util.Scanner;

Public class BinarySearch {
Public static void main (String args []) {
Scanner sc=new Scanner(System.in);
Int startN=sc. NextInt ();
Int endN=sc. NextInt ();
Int search=(int) (Math. The random () * (endN startN + 1) + startN);
Int l=endN startN + 1;
Int [] array=new int [l];
for(int i=0; IArray [I]=startN;
StartN++;
}
Int the end=l - 1, start=0, middle=0;
Boolean found=false;
Int time=1;
While (startMiddle=+ start (end)/2;
If (array (middle) & gt; Search) {
End=middle - 1;
Time++;
} else if (array (middle) & lt; Search) {
Start=middle + 1;
Time++;
} else {
If (time> 1) {
System. Out.println (" The number is: "+" \ n "search + +" It took "+ time +" tries!" );
Found=true;
} else {
System. Out.println (" The number is: "+" \ n "search + +" It took "+ time +" try!" );
Found=true;
}
}
}
}
}


CodePudding user response:

The
refer to the original poster ssdiu response:


Should be no considering the search=startN=array [0], finally end will equal to 0 directly out of the while loop,
  • Related