准备面试需要知道的经典算法--快排

一、 快速排序

快速排序使用分治法策略来把一个串行分为两个子串行,平均时间复杂度Ο(n log n)。

算法步骤:

1 从数列中挑出一个元素,称为 “基准”;

2 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区操作;

3 递归地把小于基准值元素的子数列和大于基准值元素的子数列排序。

递归实现(PHP):

function quick_sort(&$arr, $start, $end){
    $temp = $arr[$start];
    $start_index = $start;
    $end_index = $end;
    while($start_index < $end_index){
         while($arr[$end_index] >= $temp &&                    $start_index < $end_index){
             $end_index --;
         }
         if ($start_index < $end_index){
            $arr[$start_index] = $arr[$end_index];
            $start_index ++;
        }
         while($arr[$start_index] <=$temp &&     $start_index < $end_index){
             $start_index++;
         }
         if ($start_index < $end_index){
              $arr[$end_index] = $arr[$start_index];
              $end_index--;
         }
     }
     $arr[$start_index] = $temp;
     if ($start < $start_index - 1){
          quick_sort($arr, $start, $start_index - 1);
     }
     if ($end_index + 1 < $end){
          quick_sort($arr,$end_index + 1, $end);
     }
}


非递归实现:

function quick_sort(&$arr){
    $stack = array();
    array_push($stack, 0);
    array_push($stack, count($arr)-1);
    while(!empty($stack)){
        $end = array_pop($stack);
        $start = array_pop($stack);
        $start_index = $start;
        $end_index = $end;
        while($start_index < $end_index){
             while($arr[$end_index] >= $temp && $start_index < $end_index){
             $end_index --;
         }
         if ($start_index < $end_index){
             $arr[$start_index] = $arr[$end_index];
             $start_index ++;
         }
         while($arr[$start_index] <= $temp && $start_index < $end_index){
             $start_index++;
         }
         if ($start_index < $end_index){
             $arr[$end_index] = $arr[$start_index];
             $end_index--;
         }
     }
     $arr[$start_index] = $temp;
     if ($start < $start_index - 1){
         array_push($stack, $start);
         array_push($stack,$start_index - 1);
     }
     if ($end_index + 1 < $end){
          array_push($stack,$end_index + 1);
          array_push($stack,$end);
     }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值