Home >Backend Development >PHP Tutorial >How to implement selection sorting in PHP?
Selection sort is improved on the basis of Bubble sort, and only one pass exchange is performed each time it passes through the list. Simply put, the principle of selection sort is to 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. Selection sort is an unstable sorting method.
The code example of PHP selection sorting is as follows:
<?php function selection_sort($data) { for($i=0; $i<count($data)-1; $i++) { $min = $i; for($j=$i+1; $j<count($data); $j++) { if ($data[$j]<$data[$min]) { $min = $j; } } $data = swap_positions($data, $i, $min); } return $data; } function swap_positions($data1, $left, $right) { $backup_old_data_right_value = $data1[$right]; $data1[$right] = $data1[$left]; $data1[$left] = $backup_old_data_right_value; return $data1; } $my_array = array(3, 0, 2, 5, -1, 4, 1); echo "原始数组:\n"; echo implode(', ',$my_array ); echo "\n排序后数组:\n"; echo implode(', ',selection_sort($my_array)). PHP_EOL;
Output:
原始数组: 3, 0, 2, 5, -1, 4, 1 排序后数组: -1, 0, 1, 2, 3, 4, 5
This article is about PHP selection sorting The implementation method is introduced, I hope it will be helpful to friends who need it!
The above is the detailed content of How to implement selection sorting in PHP?. For more information, please follow other related articles on the PHP Chinese website!