A friend to find a job to meet the questions, notes.
It is very likely that I will meet in the future.
Problem: PHP does not use built-in functions for array sorting, possibly descending or ascending
The first method: the legendary bubbling method
Copy the Code code as follows:
function ArraySort ($data, $order = ' asc ') {
ASC Ascending desc Descending
$temp = Array ();
$count = count ($data);
if ($count <= 0)
return false; The incoming data is incorrect
if ($order = = ' asc ') {
for ($i = 0; $i < $count; $i + +) {
for ($j = $count-1; $j > $i; $j-) {
if ($data [$j] < $data [$j-1]) {
Swap the location of 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
Echo ('
');
Var_dump (ArraySort ($data, ' desc '));//Descending
The second method: Do not know what name to take a good, called the insertion Method! 囧
Copy the Code code as follows:
function Arraysort3 ($data, $order = ' asc ') {
Currently only 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 to Decrement: Judging from the high position
}
}
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
The above introduces the South row eight professional program PHP without the built-in function array sorting two algorithm code, including the South row eight Professional program content, I hope the PHP tutorial interested in a friend helpful.