Reputation: 51
im trying to implement a basic form of binary search. i created an array and filled out with linear values. Now just trying to sort through it to find a number and its index.. The problem is that it is getting stuck in a constant loop and returning zero. it goes through the nested loop because it prints but is unable to find the target value. Below is the code
for (int i= 1; i < 10000 ; i++){
studentID[i] = i;
}
Students studentIDNumber = new Students();
studentIDNumber.binarySearch(studentID, 400);
public void binarySearch(int[] studentID, int targetID){
System.out.println("helloworld");
int position = -1;
int suspect;
int suspectIndex = 0;
int lastSuspectIndex = studentID.length-1;
while(position == -1)
{
assert(suspectIndex<lastSuspectIndex);
suspectIndex = ((studentID.length-1)/2);
lastSuspectIndex =suspectIndex;
suspect=studentID[suspectIndex];
System.out.println(suspect);
if(suspect == targetID){
position = suspectIndex;
System.out.println(suspectIndex +" is where the ID #"+targetID+" is sotred");
break;
}
if(suspect < targetID){
suspectIndex= suspectIndex+(suspectIndex/2);
position = -1;
}
if(suspect > targetID){
suspectIndex= suspectIndex-(suspectIndex/2);
position = -1;}
else {
System.out.println("ID not found " );
}
}
}
Upvotes: 0
Views: 225
Reputation: 56
On this line:
suspectIndex = ((studentID.length-1)/2);
suspectIndex will be the same for every loop iteration. Initialize the variable once before the loop but not at the start of the loop itself.
Upvotes: 3