Binary search with Java, system if number not present?
Good morning,
The following:
I have an array with 25,000 fields, in which square numbers are stored in ascending order. The program currently queries the user for the number it's looking for and then systematically searches the array using approximation. I just have absolutely no idea how to implement it so that it detects when the number isn't there. My idea was to divide the variable from the last attempt by the variable from the current attempt, and if the result is 0, it should output that the number isn't there. Unfortunately, this sometimes causes it to display that the number isn't there, even though it is, whenever it searches a field next to the number being searched for. Here's the relevant part of the code:
int resultIndex; int bereich = 12500; int alg = 6250; int bereich2 = 0; while(true) { if(quadratZahlen[bereich] < zahl) { bereich = bereich + alg; alg = alg / 2; } else if(quadratZahlen[bereich] == zahl) { resultIndex = bereich; break; } else if(quadratZahlen[bereich] > zahl) { bereich = bereich / 2; alg = bereich / 2; } int test = bereich - bereich2; if (test == 0) { resultIndex = -1; break; } bereich2 = bereich; }
range2 is the variable of the last search
area of the current search
alg is only used to recalculate the range if the number was not found
resultIndex shows the position of the found number
If you want to make it much easier, then you take two indices, L and R and, depending on, R is set to the middle between L and R or vice versa.
Once L=R you can finish the loop, which corresponds to a “not found”.
P.S.: What is the meaning of looking in a list of square numbers?
Doesn’t make sense, it’s just an exercise at university. Thank you very much
Your loop needs a dynamic condition in your head. Since you keep halving the search area in a binary search, you have at some point (case) only a quantity of 1. If this is the case (and there is no find), the loop must be terminated. The variable Result index you can initialize with -1. Only at Fund is their value overwritten.
Addendum:
An iterative search could look like this:
I use two variables (start, end), which represent the boundaries of the area to be searched. With each run, they are recalculated and, on this basis, an average / anchor point (ivot) is determined.
You don't have to unlock the algorithm yourself; Implementations of binary search can be found on the Internet, eg http://www.geeksforgeeks.org .
To this end, an explanation video on the functioning of the binary search:
https://www.youtube.com/watch?v=XJUgCSejezQ
Thank you.