Can anyone explain this code. I know binary search but didn't get this point -
if(mid*mid === x) return mid
// If mid squared is greater than x then the answer must be on the left half of mid
else if(mid*mid >x) right = mid
// If mid squred is less than x then the answer must be on the right half of mid
else left = mid+1
}
return left - 1
the task says, we need
Input: x = 4 // input
Output: 2 // we have to return
else if(mid*mid >x) right = mid
if the mid * mid ( target ) is bigger we're going left side of the binary search ( in the case with numbers, not arrays, we're doing like this, if mid before was 4 , it is our input in first iteration, new value will be 2;
else left = mid+1
says, we going to the right side of the binary search, and 2 + 1 = 3 and we are going to search again through while
Can anyone explain this code. I know binary search but didn't get this point -
if(mid*mid === x) return mid
// If mid squared is greater than x then the answer must be on the left half of mid
else if(mid*mid >x) right = mid
// If mid squred is less than x then the answer must be on the right half of mid
else left = mid+1
}
return left - 1
the task says, we need
Input: x = 4 // input
Output: 2 // we have to return
if the mid * mid ( target ) is bigger we're going left side of the binary search ( in the case with numbers, not arrays, we're doing like this, if mid before was 4 , it is our input in first iteration, new value will be 2;
says, we going to the right side of the binary search, and 2 + 1 = 3 and we are going to search again through while
thanks for reply