Answer the question
In order to leave comments, you need to log in
What could be the reason for "stopping" conditions in while?
Example
I was puzzled by binary search. There was a problem - it only works "up".
Those. if in an array like [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ] I will look for 9, then it is found, but all previous digits return none.
Tried to change the cycle, the result is the same. What can be a jamb?
How it works:
Use
min = 0;
max = array length - 1 (we get the maximum index);
mid = (min + max) / 2 and round down - we get the index of the central element in the array.
When we enter a number into the search, we compare it with the element at index mid.
If the equality is true, we output the result to the console.
If the element at index mid is greater than the number we are looking for, then max = mid - 1, then find mid for the new interval and repeat until the result.
Similarly, if the element at index mid is less than the number we are looking for, then min = mid + 1, then find mid for the new interval and repeat until the result.
Answer the question
In order to leave comments, you need to log in
You set the max value to the maximum index before starting the search - excellent. But what about min - why don't you set it to 0? Forgot? Or do you think that 0 will appear there by itself? Will not appear.
UPD. Well, since you put the "vue" tag... It's
not very clear why the min and max values should be put in data - they are not used outside the binarySearchInit method. Let be local variables of this method.
Why such difficulties with a separate button for receiving data? Make array a computed property.
Supplement the question, it's a little unclear how you are looking for a nine. Try using the function to read the length of an array, taking from it the numbers you need.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question