1

I am coding my own function for a binary search algorithm and I can't seem to find the discrepancies in logic. When ever I search for 4 it does not return the ideal response.

Code Below:

var list = [1,2,3,4,6,7,13,18,19];

function binarySearch(list,number) {
    var newList = list;
    while (newList.length >= 1) {
        var halfNum = Math.round(newList.length/2);
            if (newList[halfNum] === number) {
            return "Number Found";
        } else if (newList[halfNum] < number) {
            newList = newList.slice(halfNum + 1,newList.length - 1);
        } else {
            newList = newList.slice(0,halfNum - 1);
        }
    }
}


console.log(binarySearch(list,4));
3
  • As a general debugging technique, insert console.log calls into key parts of the code to display the calculated values. This will show where things have gone awry. Commented Feb 21, 2014 at 0:48
  • @Matt Thanks and I have tried that I couldn't figure out where the fault lies in the code. Commented Feb 21, 2014 at 0:53
  • A good start would be looking at newList after the slice. Commented Feb 21, 2014 at 1:27

1 Answer 1

2

The problem here is that you are doing the ranges wrong. the javascript slice function cuts the array into the interval [start,finish), and by that I mean that it does not include the end index in the new array

So you shoudl change this:

    } else if (newList[halfNum] < number) {
        newList = newList.slice(halfNum + 1,newList.length - 1);
    } else {
        newList = newList.slice(0,halfNum - 1);
    }

To this:

    } else if (newList[halfNum] < number) {
        newList = newList.slice(halfNum + 1,newList.length);
    } else {
        newList = newList.slice(0,halfNum);
    }
Sign up to request clarification or add additional context in comments.

Comments

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.