Home > Backend Development > PHP Tutorial > Various methods of sorting arrays in php_PHP tutorial

Various methods of sorting arrays in php_PHP tutorial

WBOY
Release: 2016-07-13 16:55:55
Original
1017 people have browsed it

When we learn programming, we know that sorting methods include bubble sorting, quick sorting, selection sorting, etc., and the simultaneous sorting method Divided into two categories internal and external.

Sort method of array
Divided into two categories:
1. Internal (memory) sorting
2. External sorting (the amount of data is too large to be stored in the memory, so external sorting is required
Storage)


----------------
Sorting is a basic skill for a programmer
1: Internal sorting
(1) Commutative sorting
1. Bubble method

The default transfer of arrays is value transfer, not address transfer
We will talk about object types later. The default transfer of objects is address transfer

//Optimize, encapsulate the bubble sorting method into a function to facilitate future use

$myarr[$j]= $myarr[$j+1];
The code is as follows
 代码如下 复制代码

function bubbleSort(&$myarr){
$temp=0;//定义一个中间变量
//外层循环
for($i=0;$i for($j=0;$j $j++){
if($myarr[$j]>$myarr[$j
+1]){
$temp=$myarr[$j];
$myarr[$j]=
$myarr[$j+1];
$myarr[$j+1]=
$temp;
}

}
}
}

$arry=array(2,6,-4,7,9,0);
bubbleSort($arry);
print_r($arry);

Copy code

function bubbleSort(&$myarr){

$temp=0;//Define an intermediate variable
 代码如下 复制代码

function selectSort(&$myarr){
$temp=0;
for($i=0;$i //假设$i就是最小的数
$minval=$myarr[$i];
//记录我认为的最小数的下标
$minIndex=$i;

for($j=$i+1;$j +){
//说明我们认为的最小值,不是最小
if($minval>$myarr[$j]){

$minval=$myarr[$j];
$minIndex=$j;

}

}
//最后交换
$temp=$myarr[$i];
$myarr[$i]=$myarr[$minIndex];
$myarr[$minIndex]=$temp;
}

}

//Outer loop

for($i=0;$i for($j=0;$j $j++){

if($myarr[$j]>$myarr[$j

+1]){

$temp=$myarr[$j];
$myarr[$j+1]= $temp;

}

} } $arry=array(2,6,-4,7,9,0); bubbleSort($arry); print_r($arry); 2. Quick sorting method (magically fast, involving recursion)
3. Selection sorting method
The code is as follows
Copy code
function selectSort(&$myarr){ $temp=0; for($i=0;$i //Assume $i is the smallest number<🎜> $minval=$myarr[$i];<🎜> //Record the subscript of the smallest number I think <🎜> $minIndex=$i;<🎜> <🎜>for($j=$i+1;$j +){<🎜> //Explain that the minimum value we think is not the minimum<🎜> if($minval>$myarr[$j]){ $minval=$myarr[$j]; $minIndex=$j; } } //Final exchange $temp=$myarr[$i]; $myarr[$i]=$myarr[$minIndex]; $myarr[$minIndex]=$temp; } } 4. Insertion sort method Query speed: bubble sorting method
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