1

So I've been looking for my mistake in this code for 10-20 minutes, but I still couldn't find any mistake. However I found out (after finally adding a systemout) that somethings wrong with my "middle" Integer because it's < than the lowest number (start)

Any help is appreciated!

Here's the code:

public class BinaereSuche {

public static int intList[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};


public static int bineareSuche(int number){
    int start = 0;
    int end = intList.length -1;
    boolean found = false;

    while(found == false){ 
        int middle = (end - start) / 2; 

        if(number > intList[middle]){ 
            start = middle + 1;
        }else if(number < intList[middle]){ 
            end = middle - 1;
        }else
            return middle;
        found = true;
        System.out.println(intList[start] + " <--> " + intList[end] + " => " + intList[middle]);
    } return -1;
}

public static void main(String[] args) {
    System.out.println(bineareSuche(32));
  }
}

The sysout gives me32 <--> 512 => 16 -1 where as 32 is the start number, 512 is the end number and 16 is the middle number between 512 and 32 which is obviously wrong.

p.s. I have been looking for answeres here on SO but still couldn't help find my problem -- If anyone is curious about how it works (if you don't already know): Here's a picture

1
  • Hint: there is an unconditional found=true in your while loop. So the loop will never execute more than once. Commented Nov 1, 2015 at 21:42

1 Answer 1

1

I think this line is wrong:

int middle = (end - start) / 2; 

try:

int middle = start + (end - start) / 2; 

Consider end=10, start = 9. Your approach will calculate middle = 0.

Sign up to request clarification or add additional context in comments.

2 Comments

It's not the only bug. Try searching for another value than 32. (See my comment above.)
@WhiteViking Oh yea, sorry forgot to reply after I've changed the code. Even though I didn't quite understand why the boolean changed to true because it shouldn't have changed (?), I deleted the boolean and changed that to: ´while(start <= end){...}´ and it perfectly worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.