Simple Selection Sort (Simple Selection Sort) algorithm learning, simpleselection
The examples in this article share the specific code for simple PHP selection and sorting for your reference. The specific content is as follows:
Basic Idea:
Through the comparison between n-I keywords, the records with the minimum keyword are selected from n-I + 1 records, and the records with the I (1 <= I <= n) records are exchanged. The records are sorted after N-1 troughs are executed.
Algorithm Implementation:
<? Php // simple selection sorting // function swap (array & $ arr, $ a, $ B) {$ temp = $ arr [$ a]; $ arr [$ a] = $ arr [$ B]; $ arr [$ B] = $ temp;} // simple selection Sorting Algorithm function SelectSort (array & $ arr) {$ count = count ($ arr); for ($ I = 0; $ I <$ count-1; $ I ++) {// record the minimum subscript of all elements after the $ I element $ min = $ I; for ($ j = $ I + 1; $ j <$ count; $ j ++) {if ($ arr [$ j] <$ arr [$ min]) {$ min = $ j ;}} if ($ min! = $ I) {swap ($ arr, $ min, $ I) ;}}$ arr = array (, 2 ); selectSort ($ arr); var_dump ($ arr );
Complexity Analysis:
In the simple selection and sorting process, the number of records to be moved is relatively small. In the best case, the initial status of the records to be sorted is already in the forward order, so you do not need to move the records.
In the worst case, the initial status of the record to be sorted is the largest according to the first record, and the subsequent records are arranged in ascending order, the maximum number of records to be moved is 3 (n-1 ). The number of comparisons to be compared in the simple sorting process is irrelevant to the sequence of records to be sorted in the initial state. When I = 1, n-1 comparisons are required; when I = 2, N-2 comparisons are required; and so on, the total number of comparisons required is (n-1) + (n-2) +... + 2 + 1 = n (n-1)/2, that is, the time complexity of the comparison operation is O (n ^ 2), and the time complexity of the moving operation is O (n ).
Simple sorting is unstable.
This blog is based on "big talk Data Structure" and is only recorded here for future reference!
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.