<?php
//There is a sorted array with unique elements of length n.
//Return all the PAIRS possible that when added gives you Y.
//Sample Array: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] . (Y=110)
// 0 , 1, 2, 3, 4, 5, 6, 7, 8, 9
//$arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
$arr = [-10, -5,0,10, 15, 30, 35, 45, 60, 70, 80, 90, 100];
$sumofPair = 20;
$start = 0;
$end = count($arr) -1;
$finalarr = [];
foreach($arr as $currentval){
if($pair = binarySearch($currentval,$start,$end,$sumofPair,$arr)){
$finalarr[] = $pair;
}
}
print_r($finalarr);
function binarySearch($currentval,$start,$end,$sumofPair,$arr){
while($start <= $end){
$mid = $end - (int)($end - $start)/2;//9-0/2=4
$tofind = $sumofPair - $currentval;
if($tofind == $currentval) return;
if($arr[$mid] < $tofind){
$start = $mid + 1;
}elseif($arr[$mid] > $tofind){
$end = $mid - 1;
}else{
return [$currentval,$tofind];
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: