php冒泡排序與快速排序的例子

來源:互聯網
上載者:User
  1. function bubbingSort(array $array)

  2. {
  3. for($i=0, $len=count($array)-1; $i<$len; ++$i)
  4. {
  5. for($j=$len; $j>$i; --$j)
  6. {
  7. if($array[$j] < $array[$j-1])
  8. {
  9. $temp = $array[$j];
  10. $array[$j] = $array[$j-1];
  11. $array[$j-1] = $temp;
  12. }
  13. }
  14. }
  15. return $array;
  16. }

  17. print '

    ';
  18. print_r(bubbingSort(array(1,4,22,5,7,6,9)));
  19. print '
  20. ';
  21. ?>

複製代碼

快速排序實現原理先保證列表的前半部分都小於後半部分,然後分別對前半部分和後半部分排序,這樣整個列表就有序了。

  1. function quickSort(array $array)

  2. {
  3. $len = count($array);
  4. if($len <= 1)
  5. {
  6. return $array;
  7. }
  8. $key = $array[0];
  9. $left = array();
  10. $right = array();
  11. for($i=1; $i<$len; ++$i)
  12. {
  13. if($array[$i] < $key)
  14. {
  15. $left[] = $array[$i];
  16. }
  17. else
  18. {
  19. $right[] = $array[$i];
  20. }
  21. }
  22. $left = quickSort($left);
  23. $right = quickSort($right);
  24. return array_merge($left, array($key), $right);
  25. }

  26. print '

    ';
  27. print_r(quickSort(array(1,4,22,5,7,6,9)));
  28. print '
  29. ';
  30. ?>

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.