Home >Backend Development >PHP Tutorial >Southern BaZi professional program PHP uses two algorithm codes to sort arrays without built-in functions

Southern BaZi professional program PHP uses two algorithm codes to sort arrays without built-in functions

WBOY
WBOYOriginal
2016-07-29 08:41:471051browse

A friend encountered a test question when he was looking for a job. Please make a note.
It is very likely that I will encounter it in the future.
Problem: PHP does not use built-in functions to sort arrays, it may be in descending order or ascending order
The first method: the legendary bubbling method

Copy the codeThe code is as follows:


function arraysort($data, $order = 'asc') {
//asc ascending desc descending order
$temp = array ();
$count = count ($data);
if ($count <= 0)
return false; //Incoming Incorrect data
if ($order == 'asc') {
for($i = 0; $i < $count; $i ++) {
for($j = $count - 1; $j > ; $i; $j --) {
if ($data [$j] < $data [$j - 1]) {
//Exchange the positions of the two data
$temp = $data [$j] ;
$data [$j] = $data [$j - 1];
$data [$j - 1] = $temp;
}
}
}
} else {
for($i = 0; $ i < $count; $i ++) {
for($j = $count - 1; $j > $i; $j --) {
if ($data [$j] > $data [ $j - 1]) {
$temp = $data [$j];
$data [$j] = $data [$j - 1];
$data [$j - 1] = $temp;
}
}
}
}
return $data;
}
$data = array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12 , 34, 54, 66, 32 );
var_dump ( arraysort ( $data ) ); //Ascending order
echo ('
');
var_dump ( arraysort ( $data ,'desc') );// Descending order


Second method: I don’t know what to call it, so let’s call it insertion method!囧

Copy the code The code is as follows:


function arraysort3($data, $order = 'asc') {
//Currently only doing ascending order
$count = count ( $data );
for( $i = 1; $i < $count; $i ++) {
$temp = $data [$i];
$j = $i - 1;
while ( $data [$j] > $ temp ) {
$data [$j + 1] = $data [$j];
$data [$j] = $temp;
$j --;//Why should we decrease: judge from the high bit bit by bit
}
}
return $data;
}
$data = array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12, 34, 54 , 66, 32 );
var_dump ( arraysort3 ( $data ) ); //Ascending order

The above has introduced the two algorithm codes for sorting arrays using PHP, a professional program for arranging eight characters in the south, without using built-in functions, including the contents of the professional program for arranging eight characters in the south. I hope it will be helpful to friends who are interested in PHP tutorials.

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