#Is there any way to fix this Binary Search Algorithm?
11 messages ยท Page 1 of 1 (latest)
โ This post has been reserved for your question.
Hey @real bolt! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
public static int search(int[] array, int target) {
// get the middle index
int middleIndex = array.length/2;
boolean indexFound = false;
if (array[middleIndex] == target) {
return middleIndex;
} else {
while (middleIndex < array.length) {
System.out.println("mid index "+middleIndex);
if (array[middleIndex] == target) {
indexFound = true;
break;
}
if (array[middleIndex] < target) {
middleIndex = (middleIndex + (array.length))/2;
}
if (array[middleIndex] > target) {
middleIndex = middleIndex/2 ;
}
}
}
if(indexFound)return middleIndex;
return -1;
}
You are always just changing the middle index
but you should have a beginning and end and recompute the middleIndex as the index in the middle of that
and each step, you either set the begin or end to the middleIndex (and recompute the middleIndex)
instead of changing middle element you can just make two variables..like start and end which points first and last element in an array respectively and the mid element array.length/2...if mid>target then end = mid -1 else start = mid + 1 and your mid== target then indexFound = true; Youc can do in this way.
yah I did the correct way
low high and mid
nice ๐