Home > Backend Development > PHP Tutorial > How to implement simple bubble sorting in PHP

How to implement simple bubble sorting in PHP

墨辰丷
Release: 2023-03-28 10:14:02
Original
1424 people have browsed it

This article mainly introduces the method of simple implementation of bubble sorting in PHP, and analyzes the implementation and usage techniques of PHP bubble sorting in the form of examples. Friends in need can refer to it

The details are as follows:

<?php
$files = array("file11.txt","file22.txt","file1.txt","file2.txt");
function mySort($arr,$nat=false) {
    for($i=0;$i<count($arr);$i++) {
      for($j=0;$j<count($arr)-$i-1;$j++) {
        if($nat) {
          //按照strnatcmp()自然排序函数
          if(strnatcmp($arr[$j], $arr[$j+1])>0) {
            $tmp = $arr[$j];
            $arr[$j] = $arr[$j+1];//从小到大排
            $arr[$j+1] = $tmp;
          }
        } else {
          //按照strcmp()自然排序函数
          if(strcmp($arr[$j], $arr[$j+1])>0) {
            $tmp = $arr[$j];
            $arr[$j] = $arr[$j+1];//从小到大排
            $arr[$j+1] = $tmp;
          }
        }
      }
    }
    return $arr;
}
//Array ( [0] => file1.txt [1] => file11.txt [2] => file2.txt [3] => file22.txt )
print_r(mySort($files,false));
echo "<br/>";
//2<11
//Array ( [0] => file1.txt [1] => file2.txt [2] => file11.txt [3] => file22.txt )
print_r(mySort($files,true));
?>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHPBubble sortUsage details

Implementation and efficiency analysis of four sorting algorithms in PHP [Bubble sort, insertion sort, selection sort and quick sort]

PHP sorting AlgorithmBubble Sort(Bubble Sort)

The above is the detailed content of How to implement simple bubble 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