Skip to content

Commit b3f5ef8

Browse files
author
Openset
committed
Add BubbleSortV2
1 parent 5a116ac commit b3f5ef8

File tree

1 file changed

+44
-8
lines changed

1 file changed

+44
-8
lines changed

package/Sort/BubbleSort.php

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,22 @@
1515
* @param array $container
1616
* @return array
1717
*/
18-
function BubbleSort( array $container ) {
18+
function BubbleSort(array $container)
19+
{
1920
$count = count($container);
20-
for ( $j = 1; $j < $count; $j++ ) {
21-
for ( $i = 0; $i < $count - $j; $i++ ) {
22-
if ( $container[$i] > $container[$i + 1] ) {
21+
for ($j = 1; $j < $count; $j++) {
22+
for ($i = 0; $i < $count - $j; $i++) {
23+
if ($container[$i] > $container[$i + 1]) {
2324
$temp = $container[$i];
24-
$container[$i] = $container[$i+1];
25-
$container[$i+1] = $temp;
25+
$container[$i] = $container[$i + 1];
26+
$container[$i + 1] = $temp;
2627
}
2728
}
2829
}
2930
return $container;
3031
}
3132

32-
var_dump( BubbleSort([4,21,41,2,53,1,213,31,21,423]) );
33+
var_dump(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423]));
3334

3435
/*
3536
array(10) {
@@ -54,4 +55,39 @@ function BubbleSort( array $container ) {
5455
[9] =>
5556
int(423)
5657
}
57-
*/
58+
*/
59+
60+
// +----------------------------------------------------------------------
61+
// | 方法二
62+
// +----------------------------------------------------------------------
63+
function BubbleSortV2(array $container)
64+
{
65+
$len = count($container);
66+
// 也可以用foreach
67+
for ($i = 0; $i < $len; $i++) {
68+
for ($j = $i + 1; $j < $len; $j++) {
69+
if ($container[$i] > $container[$j]) {
70+
list($container[$i], $container[$j]) = array($container[$j], $container[$i]);
71+
}
72+
}
73+
}
74+
75+
return $container;
76+
}
77+
78+
print_r(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423]));
79+
/*
80+
Array
81+
(
82+
[0] => 1
83+
[1] => 2
84+
[2] => 4
85+
[3] => 21
86+
[4] => 21
87+
[5] => 31
88+
[6] => 41
89+
[7] => 53
90+
[8] => 213
91+
[9] => 423
92+
)
93+
*/

0 commit comments

Comments
 (0)