How to implement selection sorting in PHP?

藏色散人
Release: 2023-04-05 14:14:01
Original
3026 people have browsed it

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;
Copy after login

Output:

原始数组: 3, 0, 2, 5, -1, 4, 1 
排序后数组: -1, 0, 1, 2, 3, 4, 5
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!