Home > Article > Backend Development > PHP implements patience sort algorithm
Patience sort is a sorting algorithm inspired by the card game patience and named after it. A variant of this algorithm efficiently computes the length of the longest increasing subsequence in a given array.
The name of this algorithm comes from a simplified version of the patience card game. The game starts with a shuffled deck of cards. The cards are stacked one after another on the table according to the following rules.
Initially, there was no "heap". The first card dealt forms a new card consisting of individual cards.
Each subsequent card is placed to the far left of the existing "pile", with the value of the top card being greater than or equal to the value of the new card, or to the right of all existing "piles", thus forming New "heap".
The game is over when there are no cards left to be dealt.
This article converts this card game into a two-stage sorting algorithm as shown below. Given an array of n elements from a perfectly ordered domain, think of the array as a collection of cards and simulate the patience sorting game. When the game ends, the sorted sequence is restored by repeatedly removing the smallest visible card; in other words, performing a p-way merge of p-heaps, each of which is internally sorted.
The code example of PHP implementing the patient sorting algorithm is as follows:
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort($n) { $piles = array(); //排序成堆 foreach ($n as $x) { //二进位检索 $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } // 优先队列允许我们有效地合并堆 $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(100, 54, 7, 2, 5, 4, 1); patience_sort($a); print_r($a);
Output:
Array ( [0] => 100 [1] => 54 [2] => 7 [3] => 2 [4] => 5 [5] => 4 [6] => 1 )
This article is about the patience sort algorithm The introduction is simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of PHP implements patience sort algorithm. For more information, please follow other related articles on the PHP Chinese website!