// Given a sorted array/vector/list of distinct integers and a target value K,
// return the index if the target is found.
// If not, return the index where it would be if it were inserted in order.
// Function to find the index of k or the position where it should be inserted - Using Binary Search
function searchInsertPositionOfK($arr, $k) {
$left = 0;
$right = count($arr) - 1;
while ($left <= $right) {
$mid = $left + intdiv($right - $left, 2);
if ($arr[$mid] == $k) {
return $mid;
}
// If k is smaller, search in the left half
elseif ($arr[$mid] > $k) {
$right = $mid - 1;
}
// If k is larger, search in the right half
else {
$left = $mid + 1;
}
}
// If k is not found, return the index where it should be inserted
return $left;
}
$arr1 = [1, 3, 5, 6, 7, 8];
$k1 = 5;
echo searchInsertPositionOfK($arr1, $k1) . "\n";
$arr2 = [1, 3, 5, 6, 7, 8];
$k2 = 2;
echo searchInsertPositionOfK($arr2, $k2) . "\n";
$arr3 = [1, 3, 5, 6, 7, 8];
$k3 = 9;
echo searchInsertPositionOfK($arr3, $k3) . "\n";
/*
run:
2
1
6
*/