越简单越好!

冒泡排序和快速排序

bevin 发表于 2007-07-24 16:02 | 6次阅读 0次推荐   PHP
1 // 冒泡排序(数组排序)
2 function bubble_sort( $array )
3 {
4          $count = count ( $array );
5          if ( $count <= 0 ) return false ;
6
7          for ( $i = 0 ; $i < $count ; $i ++ ){
8                  for ( $j = $count - 1 ; $j > $i ; $j -- ){
9                          if ( $array [ $j ] < $array [ $j - 1 ]){
10                                  $tmp = $array [ $j ];
11                                  $array [ $j ] = $array [ $j - 1 ];
12                                  $array [ $j - 1 ] = $tmp ;
13                          }
14                  }
15          }
16          return $array ;
17 }
18
19 // 快速排序(数组排序)
20 function quick_sort( $array ) {
21          if ( count ( $array ) <= 1 ) return $array ;
22
23          $key = $array [ 0 ];
24          $left_arr = array ();
25          $right_arr = array ();
26
27          for ( $i = 1 ; $i < count ( $array ); $i ++ ){
28                  if ( $array [ $i ] <= $key )
29                          $left_arr [] = $array [ $i ];
30                  else
31                          $right_arr [] = $array [ $i ];
32          }
33
34          $left_arr = quick_sort( $left_arr );
35          $right_arr = quick_sort( $right_arr );
36
37          return array_merge ( $left_arr , array ( $key ) , $right_arr );
38 }
+0
发表评论
×您的大名会显示在评论处

评论内容不能少于5个字哦~~~

评论列表
当前暂无评论
发送数据中... 请求错误. 请输入评论内容和验证码后再发布 您已经参与过了,谢谢
返回顶部 ^