Home  >  Article  >  Backend Development  >  How to implement selection sorting in PHP?

How to implement selection sorting in PHP?

藏色散人
藏色散人Original
2019-03-06 13:57:423080browse

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.

How to implement selection sorting in PHP?

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(&#39;, &#39;,$my_array );
echo "\n排序后数组:\n";
echo implode(&#39;, &#39;,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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn