Two algorithm codes for sorting arrays in PHP without built-in functions_PHP tutorial

WBOY
Release: 2016-07-21 15:41:25
Original
779 people have browsed it

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 code The code is as follows:

function arraysort($data, $order = 'asc') {
//asc ascending desc descending
$temp = array ();
$count = count ( $data );
if ($count <= 0)
return false; //The data passed in is incorrect
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 This method: I don’t know what to call it, so let’s call it the insertion method!囧
Copy code The code is as follows:

function arraysort3($data, $order = 'asc') {
//Currently only sorting in 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 decrement: judge bit by bit from the high 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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321147.htmlTechArticleA 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. Question: PHP does not use built-in functions to sort arrays, it may be in descending order or ascending order. The first method...
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