PHP usort , , quicksort.
$temp == > $temp = [arr[$i] , arr[$j] , arr[$i]-arr[$j] ]
$arr = array (20, 1, 5, 10, 7, 16);
$temp=array();
for ($i = 0; $i < count($arr)-1; $i++)
{
$diff=0;
for ($j = $i+1; ($j < count($arr) && $i!=$j); $j++)
{
$diff=abs($arr[$i]-$arr[$j]);
$temp[] = array($arr[$i],$arr[$j], $diff);
}
}
usort($temp,function ($a, $b) { return $b[2] < $a[2]; });
list($x,$y,$d) = $temp[0];
echo "Related Values are $x and $y by $d";
http://ideone.com/pZ329m
20 1 5 10 7 16 //inner loop
| | | | | | $temp[]=[[20,1,19],[20,5,15],[20,10,10],...//$i=0 |// `20` is compared values from 1 onwards and the values and differences are stored in `$temp[]`
|___|____|___|___|___| //(eg., $temp=[20,1,|20-1|]) //$j=1,2,3,4,5β
| | | | | [1,5,4],[1,10,9],... //$i=1 | `1` is compared with values from 5 onwards
|____|___|___|___| //$j=2,3,4,5 βouter loop
| | | | [5,10,5],[5,7,2],... //$i=2 | `5` is compared with values from 10 onwards
|___|___|___| //$j=3,4,5 β
| | | [10,7,3],[10,16,6] //$i=3 | `10` is compared with values from 7 onwards
|___|___| //$j=4,5 β
| | [7,16,9]] //$i=4 |`7` is compared with final value `16`
|___| //$j=5 β
$temp[] differences.
$temp[] .
$temp[]
Array
(
[0] => Array
(
[0] => 7
[1] => 5
[2] => 2
)
[1] => Array
(
[0] => 7
[1] => 10
[2] => 3
)
[2] => Array
(
[0] => 16
[1] => 20
[2] => 4
)
[3] => Array
(
[0] => 5
[1] => 1
[2] => 4
)
[4] => Array
(
[0] => 10
[1] => 5
[2] => 5
)
[5] => Array
(
[0] => 16
[1] => 10
[2] => 6
)
[6] => Array
(
[0] => 7
[1] => 1
[2] => 6
)
[7] => Array
(
[0] => 16
[1] => 7
[2] => 9
)
[8] => Array
(
[0] => 10
[1] => 1
[2] => 9
)
[9] => Array
(
[0] => 10
[1] => 20
[2] => 10
)
[10] => Array
(
[0] => 16
[1] => 5
[2] => 11
)
[11] => Array
(
[0] => 7
[1] => 20
[2] => 13
)
[12] => Array
(
[0] => 5
[1] => 20
[2] => 15
)
[13] => Array
(
[0] => 16
[1] => 1
[2] => 15
)
[14] => Array
(
[0] => 1
[1] => 20
[2] => 19
)
)