Home >Backend Development >PHP Tutorial >PHP selection sorting implementation code

PHP selection sorting implementation code

WBOY
WBOYOriginal
2016-07-25 09:00:141009browse
Let me introduce you to a code example of PHP selection sorting. Friends in need can refer to it. Compared with PHP bubble sort, selection sort is a simple and intuitive sorting algorithm. working principle: First, find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence. And so on until all elements are sorted.
<?php
    //php 选择排序示例
    //bbs.it-home.org    
    function selectSort(&$arr){
        //定义进行交换的变量
        $temp=0;
        for($i=0;$i<count($arr)-1;$i++){
            //假设$i就是最小值
            $valmin=$arr[$i];
            //记录最小值的下标
            $minkey=$i;
            for($j=$i+1;$j<count($arr);$j++){
                //最小值大于后面的数就进行交换    
                if($valmin>$arr[$j]){
                    $valmin=$arr[$j];
                    $minkey=$j;
                }
            }
            //进行交换
            $temp=$arr[$i];
            $arr[$i]=$arr[$minkey];
            $arr[$minkey]=$temp;
        }
    } 
        
    $arr=array(7,5,0,4,-1);
    selectSort($arr);
    print_r($arr);
?>


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