Home > Backend Development > PHP Tutorial > php implements quick sorting

php implements quick sorting

小云云
Release: 2023-03-22 15:18:02
Original
1985 people have browsed it

Selection sort Selection sortIt works by selecting the smallest (or largest) element from the data elements to be sorted each time and storing it at the beginning of the sequence until All data elements to be sorted are arranged. Selection sort is an unstable sorting method (for example, the sequence [5, 5, 3] swaps the first [5] with [3] for the first time, causing the first 5 to move behind the second 5).

<?php
function SelectSort($arr)
 {
     $count=count($arr);
  for ($i=0; $i <$count ; $i++) { 
      //默认$i是最小的
     $min=$i;
    for ($j=$i; $j <$count; $j++) { 
        if ($arr[$min] > $arr[$j]) {
            //如果最小值大于下一个数,就立刻变值
            $min=$j;
        }
    }
    //把最小的下标换成第一个值
    if ($min!=$i) {
        list($arr[$min],$arr[$i])=[$arr[$i],$arr[$min]];
    }
  }
  return $arr;
 }
 //假设需要排序的数组
$arr=array(5,9,8,2,4,6,7,1,25,13,18,22);
$new_arr=SelectSort($arr);
print_r($new_arr);
 ?>
Copy after login

Related recommendations:

Detailed explanation of quick sort in JavaScript

php bubble, select, insert and quick sort Detailed explanation of the method

#Example of method to implement quick sort in PHP

The above is the detailed content of php implements quick sorting. 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