-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectSort.php
More file actions
49 lines (46 loc) · 843 Bytes
/
selectSort.php
File metadata and controls
49 lines (46 loc) · 843 Bytes
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
<?php
/**
* 选择排序
* @param array $arr
* @return array
*/
function selectSort($arr)
{
$count = count($arr);
if ($count < 2) {
return $arr;
}
for ($i = 0; $i < $count - 1; $i ++) {
// 当前值的位置
$key = $i;
for ($k = $i + 1; $k < $count; $k ++) {
// 相邻值进行比较,条件成立替换当前值
// 倒序 $arr[$key] < $arr[$k]
if ($arr[$key] > $arr[$k]) {
$key = $k;
}
}
if ($key != $i) {
// 交换位置
$temp = $arr[$key];
$arr[$key] = $arr[$i];
$arr[$i] = $temp;
}
}
return $arr;
}
$arr = array(
2,
13,
42,
34,
56,
23,
67,
365,
87665,
54,
68,
3
);
print_r(selectSort($arr));