-
- function arraysort($data, $order = 'asc') {
- //asc ascending desc descending order
- $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
Copy code
2. Insertion sort method
-
- 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 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 ; Helpful to everyone.
Scripting School is dedicated to you every day.
-
- >>> For more information, please view the complete list of php array sorting methods
|