The principle and code explanation of PHP fast sorting algorithm

Time:2020-4-20

Algorithm principle

The following graph is from the five minute algorithm, which demonstrates the principle and steps of the fast sorting algorithm.

Step:

Select a base value from the array

Put the greater than the reference value on the same side and the less than the reference value on the other side of the array, with the reference value in the middle position

Recursively reorder arrays on both sides of a column

code implementation


function quickSort($arr)

{

 $len = count($arr);

 if ($len <= 1) {

  return $arr;

 }

 

 $v = $arr[0];

 $low = $up = array();

 for ($i = 1; $i < $len; ++$i) {

  if ($arr[$i] > $v) {

   $up[] = $arr[$i];

  } else {

   $low[] = $arr[$i];

  }

 }

 $low = quickSort($low);

 $up = quickSort($up);

 

 return array_merge($low, array($v), $up);

}

Test code:


$startTime = microtime(1);

 

$arr = range(1, 10);

shuffle($arr);

 

echo "before sort: ", implode(', ', $arr), "\n";

$sortArr = quickSort($arr);

echo "after sort: ", implode(', ', $sortArr), "\n";

 

echo "use time: ", microtime(1) - $startTime, "s\n";

Test results:


before sort: 1, 7, 10, 9, 6, 3, 2, 5, 4, 8

after sort: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

use time: 0.0009009838104248s

Time complexity

In the worst case, the time complexity of fast sorting is O (N2), and the average time complexity is O (n * LGN).

Let’s say there are n numbers in the sequence. The time complexity of traversal once is O (n). How many times does it need to be traversed? At least LG (n + 1) times and at most N times.

1) Why LG (n + 1) times at least? Fast sorting is traversed by the divide and conquer method. We regard it as a binary tree. The number of times it needs to traverse is the depth of the binary tree. According to the definition of the complete binary tree, its depth is at least LG (n + 1). Therefore, the traversal times of fast sorting is at least LG (n + 1).

2) Why n times at most? This should be very simple, or fast sort as a binary tree, its maximum depth is n. Therefore, the traversal times of fast read sorting is n at most.

Recommended Today

Use of String

1. Use of String String s1 = “abc”;//How literals are defined String s2 = “abc”; System.out.println(s1==s2)//true, s1, s2 point to the same address   1. String is declared final and cannot be inherited2. The String class implements the Serializable interface: indicating that strings support serialization,Implements the Comparable interface: indicates that String can be compared in […]