Om3ga
Om3ga

Reputation: 32853

Binary search using javascript

I am converting c++ code into javascript that is here. The rest of the code looks fine but following function has a problem. First, second line inside while loop throws error Uncaught ReferenceError: Invalid left-hand side in assignment. When I change that to m = (A[m] >= key ? r : l); then this loop becomes infinite. How can I solve it in javascript?

    function CeilIndex(A, l, r, key) {
        var m;

        while( r - l > 1 ) {
            m = l + (r - l)/2;
            (A[m] >= key ? r : l) = m; // ternary expression returns an l-value
        }

        return r;
    }

Upvotes: 0

Views: 90

Answers (3)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

In JavaScript you can do this instead:

A[m] >= key ? r = m : l = m;

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40393

You just need to break out your left-side properly. I don't know what you're trying to do, but assuming you're assigning m to either r or l:

if (A[m] >= key) {
    r = m;
} else {
    l = m;
}

Upvotes: 1

Amadan
Amadan

Reputation: 198324

if (A[m] >= key) {
    r = m;
} else {
    l = m;
}

JavaScript can't have variable lvalues except for properties (i.e. you could do obj[A[m] >= key ? 'r' : 'l'] = m, but not what you're proposing).

Upvotes: 1

Related Questions