Home  >  Article  >  Backend Development  >  PHP implements various sorting algorithms

PHP implements various sorting algorithms

WBOY
WBOYOriginal
2016-07-25 09:12:38743browse


// Bubble sort
function BubbleSort($arr) {
// Get the total length of the array
$num = count($arr);
// Forward traversal of the array
for ($i = 1; $i $num; $i++ ) {
// Reverse traversal
for ($j = $num - 1; $j >= $ i ; $j--) {
// Compare two adjacent numbers
if ($arr[$j] $arr[$j -1]) {
// Temporarily store smaller numbers
$iTemp = $arr[$j-1];
// Put the bigger ones in front
$arr[$j-1] = $arr[$j ];
//Put the smaller one at the back
$arr[$j] = $iTemp;
}
}
}
return $arr;
}

// Exchange sorting
function ExchangeSort($arr){
$num = count($arr);
// Traverse the array
for ($i = 0;$i $num - 1 ; $i++) {
// Get the next index of the current index
for ($j = $i + 1; $j $num ; $j++) {
//Compare the values ​​of two adjacent ones
if ($arr[$j] $arr[$i ]) {
// Temporarily store smaller numbers
$iTemp = $arr[$i];
// Put the bigger ones in front
$arr[$i] = $arr[$j];
//Put the smaller one at the back
$arr[$j] = $iTemp;
}
}
}
return $arr;
}

//Selection sorting
function SelectSort($arr) {
// Get the total length of the array
$num = count($arr);
// Traverse the array
for ($i = 0;$i $num-1; $i++) {
// Temporarily store the current value
$iTemp = $arr[$i];
// Temporarily save the current location
$iPos = $i;
// Traverse the data after the current position
for ($j = $i + 1; $j $num ; $j++){
// If there is
less than the current value if ($arr[$j] $iTemp) {
// Temporary minimum value
$iTemp = $arr[$j];
// Temporary location
$iPos = $j;
}
}
// Put the current value into the calculated position
$arr[$iPos] = $arr[$i];
// Replace the current value with the calculated value
$arr[$i] = $iTemp;
}
return $arr;
}

// Insertion sorting
function InsertSort($arr){
$num = count($arr);
// Traverse the array
for ($i = 1;$i $num; $i++ ) {
// Get the current value
$iTemp = $arr[$i];
// Get the previous position of the current value
$iPos = $i - 1;
//If the current value is less than the previous value, it has not reached the beginning of the array
while (($iPos >= 0) && ($iTemp $arr[ $iPos])) {
// Put the previous value one digit back
$arr[$iPos

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
Previous article:iframe ajax call exampleNext article:iframe ajax call example