forked from m9rco/algorithm-php
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathSelectSort.php
More file actions
72 lines (65 loc) · 1.75 KB
/
SelectSort.php
File metadata and controls
72 lines (65 loc) · 1.75 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/**
* 选择排序
*
* @author ShaoWei Pu <[email protected]>
* @date 2017/6/17
* @license MIT
* -------------------------------------------------------------
* 思路分析:选择排序是不稳定的排序方法
* 大O表示: O(n 2)
* -------------------------------------------------------------
* 它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。
* 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。
*/
// +--------------------------------------------------------------------------
// | 解题方式
// +--------------------------------------------------------------------------
/**
* SelectSort
*
* @param array $container
* @return array
*/
function SelectSort(array $container)
{
$count = count($container);
for ($i = 0; $i < $count; $i++){
$k = $i;
for ($j = $i + 1; $j < $count; $j++){
if($container[$j] < $container[$k]){
$k = $j;
}
}
if($k != $i){
$temp = $container[$i];
$container[$i] = $container[$k];
$container[$k] = $temp;
}
}
return $container;
}
// +--------------------------------------------------------------------------
// | 方案测试
// +--------------------------------------------------------------------------
var_dump(SelectSort([3, 12, 42, 1, 24, 5, 346, 7]));
/*
array(8) {
[0] =>
int(1)
[1] =>
int(3)
[2] =>
int(5)
[3] =>
int(7)
[4] =>
int(12)
[5] =>
int(24)
[6] =>
int(42)
[7] =>
int(346)
}
*/