欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

Selection Sort,selectionsort

程序员文章站 2022-04-17 09:20:43
...

Selection Sort,selectionsort

Red is current min. Yellow is sorted list. Blue is current item. (picture from wikipedia, a little too fast)

10 numbers. Sort as ascend.

1. Find the min of the 10 and switch it with a[0], requires 9 times of compare

2. Find the min of the rest 9 and switch it with a[1], requires 8 times of compare

. . .

1, 10, 9

2, 9, 8

3, 8, 7

4, 7, 6

5, 6, 5

6, 5, 4

7, 4, 3

8, 3, 2

9, 2, 1

In conclusion: For 10 numbers, we need 9 times of finding the min, each has one-short amount of numbers to compare.

Implementation in PHP:

 1 php
 2 /* selection sort: 
 3     1. operate directly on the input array (&), not on a copy
 4     2. sort as ascend
 5 
 6     a is array
 7     m is length of a
 8     n is times of outer loop, which is finding min of the rest
 9     i/j is for-loop counter
10     w is for value swap
11     min is min
12     sub is index of array
13 */
14 function sortSelection(&$a){
15     $m = count($a);
16     $n = $m - 1;
17     $min;
18     $sub;
19     for($i=0; $i$n
相关标签: sort