PHP does not have two algorithms for sorting arrays with built in functions

  • 2020-03-31 20:22:00
  • OfStack

A friend seeks the examination paper that the job encounters, remark.
There's a good chance it will happen to me in the future.
Problem: PHP does not use built-in functions to sort arrays, either in descending or ascending order
The first method: the legendary bubble method
 
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]) { 
//Exchange of two data locations
$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 ('<br>'); 
var_dump ( arraysort ( $data ,'desc') );//Descending order

The second method: do not know what to name, called the insertion method! �
 
function arraysort3($data, $order = 'asc') { 
//So far we're only doing it 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: bit by bit from the top
} 
} 
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

Related articles: