Select sort,

Source: Internet
Author: User

Select sort,

The demo array is:

$ A = array (,); // The subscript is ,.

Calculation process description:

Obtain the subscript of the maximum value of an array, and exchange the unit with the last unit. Then, obtain the maximum value from the remaining data and exchange the unit with the last unit, and so on, until there is only one data left, you don't need to find it.

Demo:

Raw data: 9 3 5 8 2 7
After the first trip: 7 3 5 8 2 9
After the second trip: 7 3 5 2 8 9
After the third lie: 2 3 5 7 8 9
After the fourth round: 2 3 5 7 8 9
After the fifth tour: 2 3 5 7 8 9

 

 

 

 

 

 

Rule Description:

1. Assume that n data entries exist in the array;

2. The "number of records" for finding and exchanging the maximum unit is n-1;

3. Each trip requires the maximum number of units in "residual data", and the number of remaining data is 1 less in each trip. The first trip has n;

4. After finding the maximum unit, you must exchange the maximum unit with the last unit in the remaining array.

The code is demonstrated as follows:

<? Php $ a = array (,); // The subscript is, echo "Before sorting:"; print_r ($ ); $ n = count ($ a); // Number of for ($ I = 0; $ I <$ n-1; ++ $ I) // This is n-1 {// find the maximum unit $ max = $ a [0] at the beginning of each trip; // obtain the value of the first item $ pos = 0 for finding the maximum value; // obtain the subscript of the maximum value and the subscript of the first item for ($ k = 0; $ k <$ n-$ I; ++ $ k) {if ($ a [$ k]> $ max) {$ max = $ a [$ k]; $ pos = $ k ;}/// you can obtain the maximum value and its subscript first: the maximum unit // and then begin to exchange $ t = $ a [$ pos]; $ a [$ pos] = $ a [$ n-$ I-1]; $ a [$ n-$ I-1] = $ t;} echo "<br/> after sorting: "; print_r ($ );

The execution result is:

Before sorting: array ([0] => 9 [1] => 3 [2] => 5 [3] => 8 [4] => 2 [5] => 7)
After sorting: array ([0] => 2 [1] => 3 [2] => 5 [3] => 7 [4] => 8 [5] => 9)

 

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.