Home > php教程 > PHP开发 > body text

PHP快速排序quicksort实例详解

高洛峰
Release: 2016-12-21 13:45:14
Original
1110 people have browsed it

本文实例讲述了PHP快速排序quicksort。分享给大家供大家参考,具体如下:

quicksort

在快速排序算法中,使用了分治策略。首先把序列分成两个子序列,递归地对子序列进行排序,直到整个序列排序结束。(即一分为二的思想)

步骤如下:

在序列中选择一个关键元素做为轴;

对序列进行重新排序,将比轴小的元素移到轴的前边,比轴大的元素移动到轴的后面。在进行划分之后,轴便在它最终的位置上;

递归地对两个子序列进行重新排序:含有较小元素的子序列和含有较大元素的子序列。

比如序列$arr:

5 3 0 11 44 7 23 2 将第一个元素$arr[0] = 5 作为轴 设置标志位 low … top代表首尾
2 3 0 11 44 7 23 2 从相反方向(右)开始比较:2<5 将第一个位置替换为2,low++
2 3 0 11 44 7 23 11 从相反方向(左)开始比较直到:5<11 将最后一个位置替换为11,top–
重复以上步骤直到 low == top 把该位置替换为轴元素即5
2 3 0 5 44 7 23 11
这样就可分为两部分2 3 0 与 44 23 11
这样就可以得出递归继续开始步骤

算法实现:

class quick_sort{
    function quicksort(&$arr,$low,$top){
      if($low < $top){
        $pivotpos = $this->partition($arr,$low,$top);
        $this->quicksort($arr,$low,$pivotpos-1);
        $this->quicksort($arr,$pivotpos+1,$top);
      }
    }
    function partition(&$arr, $low ,$top){
      if($low == $top){
        return;
      }
  //   设置初始数值
      $com = $arr[$low];
      while($low!=$top){
  //      将比初始数值小的替换到左边
        while($top&&$top!=$low){
          if($com > $arr[$top]){
          $arr[$low++] = $arr[$top];
          break;
          }else{
            $top--;
          }
        }
  //      将比初始数值大的替换到右边
        while($low&&$low!=$top){
          if($com < $arr[$low]){
            $arr[$top--] = $arr[$low];
            break;
          }else{
            $low++;
          }
        }
      }
      $arr[$low] = $com;
      return $low;
    }
}
Copy after login

   

希望本文所述对大家PHP程序设计有所帮助。

更多PHP快速排序quicksort实例详解相关文章请关注PHP中文网!


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 [email protected]
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!