One, selection sort
Idea: Select the smallest (or largest) element from the data elements to be sorted each time, and store it at the beginning of the sequence until all the data elements to be sorted are exhausted
way 1 | way 2 |
function selectSort($num){ for($i = 0; $i < count($num); $i++){ for($j = $i + 1; $j < $n; $j++){ if($num[$i] > $num[$j]){ $num[$i] ^= $num[$j]; $num[$j] ^= $num[$i]; $num[$i] ^= $num[$j]; } } } return $num; } |
function selectSort($num){ for($i = 0; $i < count($num); $i++){ $k = $i; for($j = $i; $j < $n; $j++){ if($num[$k] > $num[$j]){ $k = $j; } } if($i != $k){ $num[$i] ^= $num[$k]; $num[$k] ^= $num[$i]; $num[$i] ^= $num[$k]; } } return $num; } |
Execution order:
Original array: [0]=>4 [1]=>6 [2]=>3 [3]=>5 [4]=>1 [5]=>2
1 processing:
Swap process: When i = 0, j= 2, $num[0] and $num[2] are exchanged.
When i = 0, j= 4, $num[0] and $num[4], produces swap.
Result: [0]=>1 [1]=>6 [2]=>4 [3]=>5 [4]=>3 [5]=>2
2 processing:
exchange process: when i = 1, j = 2, $num[1] and $num[2], generate exchange.
When i = 1, j = 4, $num[1] and $num [4], generate exchange.
When i = 1, j= 5, $num[1] and $num[5], generate exchange.
Result: [0]=>1 [1]=>2 [2]= >6[3]=>5[4]=>4[5]=>3
3 times of processing:
exchange process: when i = 2, j= 3, $num[2] and $num[3], generate exchange.
When i = 2, j= 4, $num[2] and $num [4], generate exchange.
When i = 2, j= 5, $num[2] and $num[5], generate exchange.
Result: [0]=>1 [1]=>2 [2]= >3[3]=>6[4]=>5[5]=>4
4 times of processing:
exchange process: when i = 3, j = 4, $num[3] and $num[4], generate exchange.
When i = 3, j = 5, $num[3] and $num [5], generate swap.
Result: [0]=>1 [1]=>2 [2]=>3 [3]=>4 [4]=>6 [5]=>5
5 times of processing:
exchange process: when i = 4, j = 5, $num[4] and $num[5], produce exchange.
Result: [0]=>1 [1]=>2 [2]= >3[3]=>4[4]=>5[5]=>6