PHP Common sorting algorithm example sharing

Source: Internet
Author: User


    • Common sorting algorithms are: bubble sort, quick sort, select sort, insert sort, here as your recent interview preparation for the study notes, but also hope to help you.

    • Requirement: An array of multiple numbers is sorted from small to large.

Sorting algorithms

"One". Bubble sort

Thinking Analysis:

Imagine a large pool of more than N-well-arranged series of hydrogen balls, the larger first out, and then the smaller one in turn. That is, each comparison of the adjacent two number, small in the front of the large after, otherwise, the position swap.

Code implementation

    • (for example, several methods of writing, pay attention to the judging conditions of the loop body) recommended the use of first to second.

    /** * Exchange method * @param array $arr target array * @param $a index A * @param $b index b * @param bool $flag Swap flag *        @return BOOL */function Swap (array & $arr, $a, $b, $flag = False) {//iterates over the element after I, as long as the element is less than the current element, then bubbles the smaller forward            if ($arr [$a] > $arr [$b]) {$temp = $arr [$a];            $arr [$a] = $arr [$b];            $arr [$b] = $temp;        $flag = true;    } return $flag;  }/** * The first way to type * @param $arr the array to sort * @return mixed returned by the array * * function Bubblesort ($arr) {$len        = count ($arr);        if ($len <= 1) {return $arr;}  The layer loop controls the number of rounds needed to bubble for ($i = 0; $i < $len-1; $i + +) {//This layer loop is used to control the number of times each round emits one count for ($j = $i + 1; $j < $len;                $j + +) {//or $this->swap ($arr, $j, $j + 1);            $this->swap ($arr, $i, $j);    }} return $arr;        }//The second way public function BubbleSort2 ($arr) {$len = count ($arr); if ($len <= 1) {return $arr;}            for ($i = 0; $i < $len-1; $i + +) {//todo The interchange flag should be false $flag = False before the start of this sequencing sequence;            for ($j = 0; $j <= $len-2; $j + +) {$flag = $this->swap ($arr, $j, $j +1, $flag);        } if (! $flag) return $arr;    } return $arr;        }//Third notation function BubbleSort3 (array & $arr) {$len = count ($arr);        if ($len <= 1) {return $arr;}                for ($i = 0; $i < $len 1; $i + +) {//$j >= 0 for ($j = $len-2; $j >= $i; $j-) {            $this->swap ($arr, $j, $j + 1);    }} return $arr;        }//Fourth notation function bubbleSort4 ($arr) {$len = count ($arr);        if ($len <= 1) {return $arr;} for ($i = 0; $i < $len-1; $i + +) {for ($j = 0; $j < $len-$i-1; $j + +) {$this->swap ($arr, $j, $j            +1);    }} return $arr; }

Summary:

    • Complexity of Time:O (n^2)

    • Add: You can use PHP built-in functions sort() or rsort() .

    • The above function sorts the indexed array by key value, assigns a new key name to the cell in the array, and removes the original key name instead of reordering. Returns TRUE if successful, otherwise FALSE

"Two". Select sort

Thinking Analysis:

Each time a minimum (or maximum) element is selected from the data element to be sorted, it is stored at the beginning of the sequence until all the data elements to be sorted are exhausted

Code implementation

        /* * @param Select the sorting method    * Each time the smallest (or largest) element is selected from the data element to be sorted, stored at the beginning of the sequence until all the data elements to be sorted are finished * */    function Selectsort ( $arr) {        //double loop complete, outer control wheel count, inner control comparison count        $len = count ($arr);        if ($len <= 1) {return $arr;}        for ($i = 0; $i < $len-1; $i + +) {            $minIndex = $i;            Find the smallest element behind I exchange for            ($j = $i + 1; $j < $len; $j + +) {                if ($arr [$minIndex] > $arr [$j]) {$minIndex                    = $j;                }            }            if ($minIndex! = $i) {                $temp = $arr [$i];                $arr [$i] = $arr [$minIndex];                $arr [$minIndex] = $temp;            }        }        return $arr;    }

Summary:

    • Complexity of Time:O (n^2)

    • an unstable sorting method (for example, sequence [5, 5, 3] swaps the first [5] with [3] for the first time, causing the first 5 to move back to the second 5).

    • In a trip, if an element is smaller than the current element, and the small element appears behind an element that is equal to the current element, then the post-swap stability is destroyed.

    • The best case is that it has been ordered, exchanged 0 times, the worst case exchange n-1 times, reverse exchange N/2 times. The number of exchanges is much less than the bubble sort, because the exchange requires more CPU time than the comparison requires more CPU time,when the n value is small, the selection sort is faster than bubble sort

"Three". Insert sort

Thinking Analysis:

    • Each step inserts a record to be sorted by the size of its key value into the appropriate position in the previously sorted file until all is inserted. (thus obtaining a new, sequential data with a number plus one)

    • Describe:

      • ⒈ starting with the first element, the element can be thought to have been sorted

      • ⒉ takes the next element and scans the sequence of elements that have been sorted from backward forward

      • ⒊ if the element (sorted) is greater than the new element, move the element to the next position

      • ⒋ Repeat step 3 until the sorted element is found to be less than or equal to the position of the new element

      • ⒌ inserting new elements into the next position

      • ⒍ Repeat steps 2~5

Code implementation

    • Here are two kinds of writing, mainly the circulation of a slightly different wording, can be used as a reference.

    /* * Insert Sort * Each step inserts a record to be sorted, by the size of its key value, into the appropriate position in the previously sorted file until all is inserted.        * */function Insertsort ($arr) {$len = count ($arr);        if ($len <= 1) {return $arr;} First default $array[0], already ordered, is ordered table for ($i = 1; $i < $len; $i + +) {if ($arr [$i] < $arr [$i-1]) {$i Nsertval = $arr [$i]; $insertVal is the number of ready to insert $insertIndex = $i-1;                    Subscript while ($insertIndex >= 0 && $insertVal < $arr [$insertIndex]) for the number of comparisons in the ordered table $arr [$insertIndex + 1] = $arr [$insertIndex]; Move the array backwards $insertIndex-;  Move the subscript forward and prepare to compare to the previous one} if ($insertIndex + 1!== $i) {$arr [$insertIndex + 1]                = $insertVal;    }}} return $arr;        } function InsertSort2 ($arr) {$len = count ($arr);        if ($len <= 1) {return $arr;} The default $array[0], already ordered, is the ordered table for ($i = 1; $i < $len; $i + +) {if ($arr [$i] < $arr[$i-1]) {$insertVal = $arr [$i];//$insertVal is the number to be inserted//$J to prepare the comparison in the ordered table//$j                    --Move the subscript forward and prepare to compare with the previous for ($j = $i-1; $j >= 0 && $insertVal < $arr [$j]; $j-) {            $arr [$j +1]= $arr [$j];//to move the array backwards} $arr [$j + 1] = $insertVal;    }} return $arr; }

Summary:

    • Complexity of Time:O (n^2)

    • Space complexity:O (1) (used to record data that needs to be inserted)

    • A stable sorting method

    • The algorithm is suitable for ordering small amounts of data

    • If the cost of the comparison operation is larger than the exchange operation, a binary lookup method can be used to reduce the number of comparison operations. The algorithm can be thought of as a variant of the insertion sort, called a binary lookup sort.

"Four". Quick sort

Thinking Analysis:

    • Divide the sorted data into separate parts by a single trip, with all the data in one part smaller than the rest of the data.

    • Then the two parts of the data are quickly sorted by this method, and the whole sorting process can be carried out recursively to achieve the whole data into ordered sequence.

Code implementation

    • Note: Most online for quick_sort2() this kind of writing, feel is not the original algorithm description, suggestions can be used for reference.

    • Perhaps the code is quick_sort() deficient, not found to have a faster sorting effect, awkward.

    /** * @param $arr target array * @param int $l left coordinates * @param $r right coordinates when initializing an incoming array, $r = count ($arr)-1 * @return Mix        Ed */Public Function Quick_sort (& $arr, $l =0, $r) {$length = count ($arr); First determine if you need to proceed with recursive egress: array length is 1, return the array directly if (!is_array ($arr) | |        $length <= 1) {return $arr;}            if ($l < $r) {$i = $l;            $j = $r;            $baseVal = $arr [$l];  while ($i < $j) {//right-to-left find the first number less than $baseval while ($i < $j && $arr [$j]                >= $baseVal) $j--;                if ($i < $j) $arr [$i + +] = $arr [$j];                From left to right, find the first number of $baseval ($i < $j && $arr [$i] < $baseVal) $i + +;            if ($i < $j) $arr [$j--] = $arr [$i];            } $arr [$i] = $baseVal; $this->quick_sort ($arr, $l, $i-1); Recursive call $this->qUick_sort ($arr, $i + 1, $r);        return $arr;        }/* * Quick Sort * */Public Function Quick_sort2 ($arr) {$length = count ($arr); First determine if you need to proceed with recursive egress: array length is 1, return the array directly if (!is_array ($arr) | |        $length <= 1) {return $arr;}        Select the first element as a datum $baseValue = $arr [0];  Traverse all elements except the ruler, put two arrays in the size relationship//Initialize two arrays $LEFTARR = array ();  $RIGHTARR less than the base = Array (); Greater than///use a For loop to traverse the selected Datum as the object of comparison for ($i = 1; $i < $length; $i + +) {if ($arr [$i] < $baseVal            UE) {//Put in the left array $leftArr [] = $arr [$i];            } else {//put in the right array $rightArr [] = $arr [$i];        }}//Do the same for the left and right arrays by recursively calling this function $leftArr = $this->quick_sort2 ($LEFTARR);        $RIGHTARR = $this->quick_sort2 ($RIGHTARR);    Merge left ruler to the right, Note: Array ($baseValue), associated with duplicate data return Array_merge ($LEFTARR, Array ($baseValue), $RIGHTARR); }

Summary:

    • A sort algorithm that doesn't waste space and can be faster

    • Worst time Complexity O (n^2)with an average time complexity of O (nlogn)

    • Featured Article-Sitting on the toilet see algorithm: Quick Sort (note: The algorithm logic is not the standard logic, suggest reading the bottom of the comments, can do reference)

"Five". Counting sort

Thinking analysis

    • The count sort uses an extra array of C, where the I element is the number of elements in the array A to be sorted with the value equal to I. The elements in a are then ranked in the correct position according to the array C. It can only sort integers

    • Algorithm Description:

      • Find the largest and smallest elements in the array to be sorted;

      • The number of occurrences of each element in the statistic array that is I, in the array C;

      • Summation of all counts (starting with the first element in C, each item and the previous one);

      • Reverse-Populate the target array: Place each element I in the C (i) of the new array, subtract C (i) by 1 for each element placed

Code implementation

    /**     * Count Sort     * @param $arr     * @return Array     *    /function Countingsort ($arr)    {        $len = count ($ ARR);        if ($len <= 1) return $arr;        Find the maximum and minimum values in the array to be sorted        $min = min ($arr);        $max = max ($arr);        Calculates the number of each element in the array to be sorted        $COUNTARR = Array ();        for ($i = $min; $i <= $max; $i + +)        {            $COUNTARR [$i] = 0;        }        foreach ($arr as $v)        {            $COUNTARR [$v] + =  1;        }        $RESARR = Array ();        foreach ($countArr as $k = = $c) {for            ($i = 0; $i < $c; $i + +)            {                $RESARR [] = $k;            }        }        return $RESARR;    }

Summary:

    • The core of a count sort is to convert the input data value into a key stored in an additional array space.
      As a sort of linear time complexity, counting ordering requires that the input data be an integer with a definite range.

    • Count sort is not a comparison sort, sort faster than any comparison sort algorithm

    • Best case: T (n) = O (n+k)
      Worst case: T (n) = O (n+k)
      Average condition: T (n) = O (n+k)

    • Restrictive conditions a lot of attention

"Six". Bucket sort

Thinking analysis

    • Assuming that the input data is uniformly distributed, the data is divided into a finite number of buckets, and each bucket is sorted separately (it is possible to use a different sorting algorithm or recursively continue to sort by the bucket)

    • Algorithm description

      • Set a quantitative array as an empty bucket;

      • Traverse the input data, and put the data into the corresponding bucket one by one;

      • Sort each bucket that is not empty;

      • From a bucket that is not empty, stitch up the sorted data.

Code implementation

    /** * Bucket Sorting design * @param $arr target array * @param int $bucketCount number of barrels allocated (integer) * @return Array */public        function Bucketsort ($arr, $bucketCount = ten) {$len = count ($arr);        $max = max ($arr) +1;        if ($len <= 1) {return $arr;}        Fill Cask $arrFill = Array_fill (0, $bucketCount, []);            Start marking cask for ($i = 0; $i < $len; $i + +) {$key = Intval ($arr [$i]/($max/$bucketCount));            Array_push ($arrFill [$key], $arr [$i]); The TODO test found: If called here, it takes twice/*if (count ($arrFill [$key])) {$arrFill [$key] = $this->insertsort ($arrF            ill[$key]); }*/}//Sort each bucket that is not empty foreach ($arrFill as $key = + $f) {if (count ($f)) {$ar            rfill[$key] = $this->insertsort ($f);                }}//Start taking data from the cask for ($i = 0; $i < count ($arrFill); $i + +) {if ($arrFill [$i]) { for ($j = 0; $j <= count ($arrFill[$i]);  $j + +) {//This line is primarily used to control the output of multiple numbers if ($arrFill [$i] [$j]) {$arrBucket [] =                    $arrFill [$i] [$j];        }                }            };    } return $arrBucket; }

Note :

    • The above code is my design based on the definition of the bucket sort, because most of the PHP code on the web feels out of spec, where the insertSort() insertion sort written in the borrowed text

    • The test found that this method takes much longer than it does countingSort() , and is not recommended for reference only.

Summary :

    • When the input element is an integer of n 0 to K, its run time is O (n + k). The count sort is not a comparison sort, and the sort is faster than any comparison sort algorithm. Because the length of the array C used to count depends on the range of data in the array to be sorted (equal to the difference between the maximum and minimum values of the array to be sorted plus 1), this makes the count sort for arrays with a large data range, which requires a lot of time and memory.

    • A stable sorting method

    • Bucket sort is an upgraded version of counting sort

    • Best case: T (n) = O (n+k)
      Worst case: T (n) = O (n^2)
      Average condition: T (n) = O (n+k)

Appendix

Summary of the "1" sorting algorithm

"2" Self-analysis

    • Here is an online majority as a "bucket sort" of similar code snippets, the individual is not described in the description of the sorting algorithm, but it is related to the "counting sort" more fit.

   /**     * @param $arr target array     * @return sorted array returned by array *    /Public Function Borcsort ($arr)    {        $len = count ($arr);        $max = max ($arr);        if ($len <= 1) {return $arr;}        Filling cask        $arrFill = Array_fill (0, $max, 0);        for ($i = 0; $i < $len; $i + +)        {            $arrFill [$arr [$i]] + +;        }        Start taking out data for        ($i = 0; $i <= $max; $i + +)        {            for ($j = 1; $j <= $arrFill [$i]; $j + +)            {//This line is mainly used to control Output multiple digital                $arrRes [] = $i;            }        }        return $arrRes;    }

"3" Elapsed time Test

    • In order to compare the time size of several algorithms, I randomly generated a number of 10000, the value of the test array of 300 or less, the algorithm used in this article is as follows:

Bucketsort spents: 1013.6640071869 mscountingsort spents: 5.6858062744141 msquick_sort spents: 66540.108919144 msselectSort Spents: 15234.955072403 msbubblesort spents: 162055.89604378 msinsertsort spents: 12029.093980789 Ms built-in sort time: 3.0169486999512 ms
    • Therefore, it is recommended to use built-in functions for array sorting of simple requirements sort() .

"4" reference article

    • Ten Classic sorting Algorithms summary (JavaScript description) " Recommended "

    • Ten classic sorting Algorithms PHP Implementation Tutorial (note the bottom of the article directory)

    • Comparison of several sort algorithms of PHP

"5" hint

    • This article is mainly for the purpose of learning

    • If you're tired, write this.

    • If you see errors and opinions, hope to give reminders, common progress, Thanks ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.