Home  >  Article  >  Backend Development  >  PHP simple sorting bubble sort and selection sort

PHP simple sorting bubble sort and selection sort

WBOY
WBOYOriginal
2016-08-08 09:23:56916browse
<?php

$arr = array(100,2,4,5,6,1,7,3);
var_dump($arr);
$sort =  fn_sort($arr);
var_dump($sort);

$selectorsort = fn_selectsort($arr);
var_dump($selectorsort);


/**
 * 冒泡排序  每相邻的两位数组进行比较,比较大的放后面
 */
//$arr = array(100,2,4,5,6,1,7,3);   
//array(2,4,5,6,1,7,3,100)  第一遍
//array(2,4,5,1,6,3,7,100)  第二遍
//array(2,4,5,1,3,6,7,100)  第三遍
//array(2,4,1,3,5,6,7,100)  第四遍
//...
//array(1,2,3,4,5,6,7,100)  最后一遍

function fn_sort($arr){
    for($i = 0;$i < (count($arr)); $i++){
        for($j = $i;$j < count($arr);$j++){
            if($arr[$i] > $arr[$j]){
                $temp = $arr[$i];
                $arr[$i] = $arr[$j];
                $arr[$j]  = $temp;
            }
        }
        
    }
    return $arr;
}


/**
 * 选择排序排序selectsort  关键是找到最小数组的下标
 */
//$arr = array(100,2,4,5,6,1,7,3);   
//array(1,2,4,5,6,100,7,3)  第一遍
//array(1,2,4,5,6,100,7,3)  第二遍
//array(1,2,3,5,6,100,7,4)  第三遍
//array(1,2,3,4,6,100,7,5)  第四遍
//...
//array(1,2,3,4,5,6,7,100)  最后一遍
function fn_selectsort($arr){
    for($i = 0; $i < count($arr); $i++){
        $min = $i;
        for($j = $i+1; $j < count($arr); $j++){
            if($arr[$min] > $arr[$j]){
                $min = $j;  //找到最小的那个数组下标
            }
        }
        
        //如果已经找到了最小数组下标,就替换当前数组与找到的最小数组进行替换
        if($min != $i){
            $temp  = $arr[$i];
            $arr[$i] = $arr[$min];
            $arr[$min] = $temp;
        }
        
    }
    return $arr;
}
?>


by:19 material

The above introduces the bubble sorting and selection sorting of PHP simple sorting, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

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