欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP快速排序算法實(shí)例分析

 更新時(shí)間:2018年07月10日 11:42:05   作者:CyborgLin  
這篇文章主要介紹了PHP快速排序算法,結(jié)合實(shí)例形式分析了快速排序的原理、步驟及相關(guān)php定義與使用操作技巧,需要的朋友可以參考下

本文實(shí)例講述了PHP快速排序算法。分享給大家供大家參考,具體如下:

快速排序:在無(wú)序的數(shù)組$data中,選擇任意一個(gè)值作為對(duì)比值,定義i為頭部檢索索引,j為尾部檢索索引,

算法步驟:

(1)初始化對(duì)比值$value=$data[0],$i=1,$j=count($data)-1

(2)首先從尾部開(kāi)始檢索,判斷$data[$j]是否小于$value,若不小于則$j--,繼續(xù)檢索,直到找到比$value小的坐標(biāo)

(3)這時(shí)開(kāi)始頭部檢索,判斷$data[$i]是否大于$value,若不大于則$i++,繼續(xù)檢索,直到找到比$value大的坐標(biāo)

(4)這時(shí)$data[$j]$data[$i]的值相互交換,即把比$value大的放到右邊,把比$value小的放到左邊

(5)重復(fù)3、4直到$i==$j

(6)這時(shí)已經(jīng)把比$value大的放到右邊,把比$value小的放到左邊,確定了中間的坐標(biāo)位置為$i,中間值為$value,把$data[$i]的值與$data[0]的值交換,因?yàn)橹虚g值為$value,需要把$value挪到數(shù)組的中間坐標(biāo)

(7)數(shù)組分成左右2個(gè)無(wú)序的數(shù)組,再分別遞歸執(zhí)行1-6,直到數(shù)組長(zhǎng)度為1

Tips:快速排序的中文定義百度下會(huì)更清楚

代碼:

<?php
header("Content-type: text/html; charset=utf-8");
function quickSort($data, $startIndex, $endIndex){
 if($startIndex < $endIndex){
  $value = $data[$startIndex]; // 對(duì)比值
  $startT = $startIndex + 1;
  $endT = $endIndex;
  while ($startT != $endT) {
   // 找到比對(duì)比值小的坐標(biāo)
   while ($data[$endT] > $value && $endT > $startT){
    $endT--;
   }
   // 找到比對(duì)比值大的左邊
   while ($data[$startT] < $value && $startT < $endT){
    $startT++;
   }
   if($endT > $startT){
    $temp =$data[$startT];
    $data[$startT] = $data[$endT];
    $data[$endT] = $temp;
   }
  }
  // 防止數(shù)組已經(jīng)排序好的情況
  if($data[$startT] < $value){
   $data[$startIndex] = $data[$startT];
   $data[$startT] = $value;
  }
  $data = quickSort($data, $startIndex, $startT - 1);
  $data = quickSort($data, $startT + 1, $endIndex);
  return $data;
 }else{
  return $data;
 }
}
$data = array(10, 5, 30, 22, 1, 42, 14, 34, 8, 13, 28, 36, 7);
$data = quickSort($data, 0, count($data) - 1);
var_dump($data);

運(yùn)行結(jié)果:

array(13) {
  [0]=>
  int(1)
  [1]=>
  int(5)
  [2]=>
  int(7)
  [3]=>
  int(8)
  [4]=>
  int(10)
  [5]=>
  int(13)
  [6]=>
  int(14)
  [7]=>
  int(22)
  [8]=>
  int(28)
  [9]=>
  int(30)
  [10]=>
  int(34)
  [11]=>
  int(36)
  [12]=>
  int(42)
}

PS:這里再為大家推薦一款關(guān)于排序的演示工具供大家參考:

在線(xiàn)動(dòng)畫(huà)演示插入/選擇/冒泡/歸并/希爾/快速排序算法過(guò)程工具:
http://tools.jb51.net/aideddesign/paixu_ys

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php排序算法總結(jié)》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論