When learning PHP, you may encounter a PHP sorting problem, here will introduce a solution to the problem of PHP sorting, here to share with you. Every year always go out look at the data structure, each time always feel that many things did not learn, alas.
Today paste just use PHP implementation of 4 sorting algorithm, the other heap sort and merge sort is not written. Insert Sort, select sort, bubble sort, time complexity seems to be O (N2), so the actual meaning is not significant, in the actual test, I to 3,000 elements of the array, the three sorting algorithm takes 80 seconds or so, and the fast sort only takes 8 seconds, the gap is relatively large, interested can test their own. Let's take a closer look at the implementation of your PHP sorting algorithm.
-
- Insert sort (one-dimensional array)
- function Insert_sort ($arr) {
- $ Count Count = count ($arr);
- For ($i=1; $i<$count; $i + +) {
- $ tmp = $arr [$i];
- $ J = $i-1;
- While ($arr [$j] > $tmp) {
- $arr [$j +1] = $arr [$j];
- $arr [$j] = $tmp;
- $j--;
- }
- }
- return $arr;
- }
- Select sort (one-dimensional array)
- function Select_sort ($arr) {
- $ Count Count = count ($arr);
- For ($i=0; $i<$count; $i + +) {
- $ k = $i;
- For ($J= $i +1; $j<$count; $j + +) {
- if ($arr [$k] > $arr [$j])
- $ k = $j;
- if ($k! = $i) {
- $ tmp = $arr [$i];
- $arr [$i] = $arr [$k];
- $arr [$k] = $tmp;
- }
- }
- }
- return $arr;
- }
- Bubble sort (one-dimensional array)
- function Bubble_sort ($array) {
- $ Count Count = count ($array);
- if ($count <= 0) return false;
- For ($i=0; $i<$count; $i + +) {
- For ($J= $count-1; $j>$i; $j-) {
- if ($array [$j] < $array [$j-1]) {
- $ tmp = $array [$j];
- $array [$j] = $array [$j-1];
- $array [$j-1] = $tmp;
- }
- }
- }
- return $array;
- }
- Quick sort (one-dimensional array)
- function Quick_sort ($array) {
- if (count ($array) <= 1) return $array;
- $ Key = $array [0];
- $ Left_arr = Array ();
- $ Right_arr = Array ();
- For ($i=1; $i<count($array); $i + +) {
- if ($array [$i] <= $key)
- $left _arr[] = $array [$i];
- Else
- $right _arr[] = $array [$i];
- }
- $ Left_arr = Quick_sort ($left _arr);
- $ Right_arr = Quick_sort ($right _arr);
- Return Array_merge ($left _arr, Array ($key), $right _arr);
- }
- ?>
http://www.bkjia.com/PHPjc/446512.html www.bkjia.com true http://www.bkjia.com/PHPjc/446512.html techarticle When learning PHP, you may encounter a PHP sorting problem, here will introduce a solution to the problem of PHP sorting, here to share with you. Every year always go out to see the data ...