In fact, the reason why quick sorting is called fast is that Bubble Sorting only exchanges the positions of two adjacent values for each comparison, so that each value must be moved to the corresponding position in its final sorting result, it may take many times
In fact, the reason why quick sorting is called fast is that Bubble Sorting only exchanges the positions of two adjacent values for each comparison, so that each value must be moved to the corresponding position in its final sorting result, it may take many times
Concept
Here we use a diagram of Baidu encyclopedia, which is very vivid:
The quick sorting algorithm is an optimization of the bubble algorithm. His idea is to first split the array and put the large element values into a temporary array, place a small element value in another temporary array (this split point can be any element value in the array, usually with the first element, that is, $ array [0]). then, we continue to split the two temporary arrays and merge the small array elements and the large array elements. The recursive idea is used here.
PHP implementation
The Code is as follows:
/*
Quick sorting
*/
Function quickSort ($ array)
{
If (! Isset ($ array [1])
Return $ array;
$ Mid = $ array [0]; // gets a keyword for segmentation, usually the first element.
$ LeftArray = array ();
$ RightArray = array ();
Foreach ($ array as $ v)
{
If ($ v> $ mid)
$ RightArray [] = $ v; // put the number larger than $ mid into an array.
If ($ v <$ mid)
$ LeftArray [] = $ v; // put a number smaller than $ mid into another Array
}
$ LeftArray = quickSort ($ leftArray); // Splits a small array again.
$ LeftArray [] = $ mid; // Add the split element to the back of a small array. you can't forget it.
$ RightArray = quickSort ($ rightArray); // splits the larger array again.
Return array_merge ($ leftArray, $ rightArray); // combine two results
}
Comparison with the bubble Algorithm
Here I have made a comparison with the sorting implemented by the bubble algorithm. It can be seen that this algorithm is much more efficient than the bubble algorithm.
The Code is as follows:
$ A = array_rand (range (1500), 1600); // If the bubble algorithm contains more than elements, the system prompts insufficient memory, however, to measure the difference between the two, it is set to 1500 to ensure that the bubble algorithm can also be executed.
Shuffle ($ a); // gets an array that has broken the order
$ T1 = microtime (true );
QuickSort ($ a); // quick sorting
$ T2 = microtime (true );
Echo ($ t2-$ t1) * 1000). 'Ms
';
Require ('./maopao. php'); // here we reference the sort of the bubble algorithm I wrote earlier.
$ T1 = microtime (true );
MaoPao ($ a); // bubble
$ T2 = microtime (true );
Echo ($ t2-$ t1) * 1000). 'ms ';
Running result:
The Code is as follows:
12.10880279541 ms
772.64094352722 ms