PHP simple sorting bubble sort and selection sort

巴扎黑
Release: 2016-11-11 09:51:52
Original
1587 people have browsed it

Php code

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


Related labels:
php
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!