Is there any way to fix this Binary Search Algorithm?

I am trying to make a binary search but it has problems
7 Replies
JavaBot
JavaBot5mo ago
This post has been reserved for your question.
Hey @Rag...JN 🌌 🦡 👽 💰! Please use /close or the Close Post button 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.
Rag...JN 🌌 🦡 👽 💰 🐊
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;
}
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;
}
dan1st
dan1st5mo ago
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)
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
Rag...JN 🌌 🦡 👽 💰 🐊
yah I did the correct way low high and mid
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot5mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server