sort

WBOY
Release: 2016-07-25 08:49:54
Original
826 people have browsed it
  1. // 选择排序 不稳定排序
  2. function selection_sort($array)
  3. {
  4. $max = count($array) - 1;
  5. for($i = 0; $i < $max; $i++)
  6. {
  7. $min = $i;
  8. for($j = $i + 1; $j <= $max; $j++)
  9. {
  10. if($array[$j] < $array[$min])
  11. {
  12. $min = $j;
  13. }
  14. }
  15. if($min != $i)
  16. {
  17. $temp = $array[$min];
  18. $array[$min] = $array[$i];
  19. $array[$i] = $temp;
  20. }
  21. }
  22. return $array;
  23. }
  24. // foreach while 插入排序
  25. function insertsort($arr)
  26. {
  27. foreach($arr as $k => $v)
  28. {
  29. $i = $k - 1;
  30. while($i > -1 && $v < $arr[$i])
  31. {
  32. $next = $arr[$i + 1];
  33. $arr[$i + 1] = $arr[$i];
  34. $arr[$i] = $next;
  35. $i--;
  36. }
  37. }
  38. return $arr;
  39. }
  40. // for while 插入排序
  41. function insertsort1($arr)
  42. {
  43. $max_key = count($arr) - 1;
  44. for($i = 1; $i <= $max_key; $i++)
  45. {
  46. $j = $i - 1;
  47. $current = $arr[$i];
  48. while($j >= 0 && $arr[$j] > $current)
  49. {
  50. $temp = $arr[$j+1];
  51. $arr[$j+1] = $arr[$j];
  52. $arr[$j] = $temp;
  53. $j--;
  54. }
  55. }
  56. return $arr;
  57. }
复制代码


Related labels:
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