PHP快速排序quicksort实例详解
本文实例讲述了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; } }
希望本文所述对大家PHP程序设计有所帮助。
更多PHP快速排序quicksort实例详解相关文章请关注PHP中文网!

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

AI Hentai Generator
Générez AI Hentai gratuitement.

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)