#Is there any way to fix this Binary Search Algorithm?

11 messages ยท Page 1 of 1 (latest)

real bolt
#

I am trying to make a binary search but it has problems

onyx stratusBOT
#

โŒ› This post has been reserved for your question.

Hey @real bolt! 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.

real bolt
#

    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;
    }
manic delta
#

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)

barren totem
real bolt
#

low high and mid

barren totem