找出數與數之間相差最小值


原整標題應該是這樣子?
找出數與數之間相差最小中最先出現的兩個數字
記錄一下吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
/*\
: abs 為確保不會有負數
: 結果:
: 3 - 3 = 0 << 4, 3, 5, 2, 0, 3, 7, 0, 7, 5
: 0 - 0 = 0 << 0, 0, 2, 3, 3, 4, 5, 5, 7, 7
\*/

// 測試數組
$test_data = array(4, 3, 5, 2, 0, 3, 7, 0, 7, 5);
$data_length = count($test_data);

// 以窮舉的方法將前後兩數相減作比較,找出最小值
$current_a = $test_data[0];
$current_a = $test_data[1];
$current_min = abs($current_a - $current_b);
for($i=1; $i<$data_length - 1; $i++) {
for($j=$i + 1; $j<$data_length; $j++) {
$temp_a = $test_data[$i];
$temp_b = $test_data[$j];
$diff_min = abs($temp_a - $temp_b);

if ($diff_m < $current_min) {
$current_min = $diff_min;
$current_a = $temp_a;
$current_b = $temp_b;
}
}
}

echo $current_a,' - ',$current_b,' = ',$current_min,' << ',implode(", ", $test_data),"\n";

// 重新排序,由小到大,同時捨棄原有的鍵值,再由零開始為鍵值
sort($test_data);

// 以窮舉比較前後位置,相減後找出最小值,
// 少了一次迴圈.但結果因排序的影響而變了
$current_a = $test_data[0];
$current_a = $test_data[1];
$current_min = abs($current_a - $current_b);
for($i=1; $i<$data_length; $i++) {
$temp_a = $test_data[$i];
$temp_b = $test_data[$i-1];
$diff_min = abs($temp_a - $temp_b);

if ($diff_m < $current_min) {
$current_min = $diff_min;
$current_a = $temp_a;
$current_b = $temp_b;
}
}

echo $current_a,' - ',$current_b,' = ',$current_min,' << ',implode(", ", $test_data),"\n";
?>