moon
moon

Reputation: 59

Issue with Binarysearch-Algorithm code

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

Upvotes: 1

Views: 51

Answers (1)

Peter de Rivaz
Peter de Rivaz

Reputation: 33509

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.

Upvotes: 1

Related Questions