0
votes

I'm trying to do a binary search in a for loop. However, flash does not like the following for loop.

for(var select:int = Math.floor((min + max / 2)), var turns:int = 0; turns < input.length / 2 + 1; turns++, select= Math.floor((min + max / 2))){
    if(input[select] > want){
        max = select;
    } else if (input[select] < want){
        min = select;
    } else {
        return select;
    }
}

On the first line I get 1084: Syntax error: expecting identifier before var. I think I know why (I'm using , to separate the different statements), but how do I fix it? ; won't work since it's what the for loop uses.

( var select:int = Math.floor((min + max / 2)) ; var turns:int = 0); turns < input.length / 2 + 1; //etc

does not work either.

2

2 Answers

2
votes

Simply ditching the second var (after the comma) should work I believe will do it:

for(var select:int = Math.floor((min + max / 2)), turns:int = 0; turns < input.length / 2 + 1; turns++, select= Math.floor((min + max / 2))){
    if(input[select] > want){
        max = select;
    } else if (input[select] < want){
        min = select;
    } else {
        return select;
    }
}
0
votes

Do you have to do this as a for loop? This would work much better as a recursive function.

Here it is as a for loop. Try pulling the select variable outside the scope of the for loop.

var select: int = Math.floor((min+max/2));
for(var turns:int = 0; turns < input.length / 2 + 1; turns++){

    if(input[select] > want){
        max = select;
        select= Math.floor((min + max / 2))
    } else if (input[select] < want){
        min = select;
        select= Math.floor((min + max / 2))
    } else {
       return select;
    }
}