Example of php array sorting (without built-in functions)

WBOY
Release: 2016-07-25 09:04:06
Original
1309 people have browsed it
  1. function arraysort($data, $order = 'asc') {
  2. //asc ascending desc descending order
  3. $temp = array ();
  4. $count = count ($data);
  5. if ($count <= 0)
  6. return false; //The data passed in is incorrect
  7. if ($order == 'asc') {
  8. for($i = 0; $i < $count; $i ++) {
  9. for($j = $count - 1; $j > $i; $j --) {
  10. if ($data [$j] < $data [$j - 1]) {
  11. //Exchange the positions of the two data
  12. $temp = $data [$j];
  13. $data [$j] = $data [$j - 1];
  14. $data [$j - 1] = $temp;
  15. }
  16. }
  17. }
  18. } else {
  19. for($i = 0; $i < $count; $i ++) {
  20. for($j = $count - 1; $j > $i; $j --) {
  21. if ($data [$j] > $data [$j - 1]) {
  22. $temp = $data [$j];
  23. $data [$j] = $data [$j - 1];
  24. $data [$j - 1] = $temp;
  25. }
  26. }
  27. }
  28. }
  29. return $data;
  30. }
  31. $data = array (7, 5, 3, 8, 9, 1, 5 , 3, 1, 24, 3, 87, 0, 33, 1, 12, 34, 54, 66, 32 );
  32. var_dump ( arraysort ( $data ) ); //Ascending order
  33. echo ('
    ' );
  34. var_dump ( arraysort ( $data ,'desc') ); // Descending order
Copy code

2. Insertion sort method

  1. function arraysort3($data, $order = 'asc') {
  2. //Currently only doing ascending order
  3. $count = count ( $data );
  4. for($i = 1 ; $i < $count; $i ++) {
  5. $temp = $data [$i];
  6. $j = $i - 1;
  7. while ( $data [$j] > $temp ) {
  8. $data [$j + 1] = $data [$j];
  9. $data [$j] = $temp;
  10. $j --;//Why decrement: judge bit by bit from the high bit
  11. }
  12. }
  13. return $data;
  14. }
  15. $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.
  16. >>> For more information, please view the complete list of php array sorting methods

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!