Selection Sort)
Core Idea of the algorithm: select the record with the minimum keyword in n-I + 1 (I> = 1) for each record as the I record in the sequence
Simple selection operation: by comparing the n-I keywords, the minimum keyword record is selected from the n-I + 1 record, and exchange with the I (1 <= I <= n) records. First, let's look at the code for sorting by choice:
Int SelectSort (MergeType * L) {int min = 0; if (! L-> elem) {return-1;}/* comparison times: n-1 + N-2 + 1 + 0 = n * (n-1) /2 */for (int I = 0; I <L-> len-1; I ++) // each number {min = I; for (int j = I + 1; j <L-> len; j ++) // each number {if (L-> elem [j] <L-> elem [I]) {min = j; // swap (L-> elem [I], L-> elem [j]);} swap (L-> elem [I], l-> elem [min]);} return 0 ;}Here, the smallest value is placed at the I-th position ~ Look at a simple instance with the smallest choice in the len-1
...for (int i=0; i
L.elem[j]}}...
Here I! = J is used to avoid switching yourself. Here, let's take a look at the special characteristics of the for loop of the bubble algorithm.
Let's look at the time complexity: The worst case comparison times = (n-1) + (n-2) + ...... + 1 + 0 = n * (n-1)/2 = O (n ^ 2)
For (I = 0; I <= L-> len-1; I ++) // each trip {for (j = 0; j <L-> len-1-i; j ++) // each number {if (L-> elem [j + 1] <L-> elem [j]) {SWAP (L-> elem [j + 1], L-> elem [j]) ;}}Bubble is to sink the maximum number into the lowest end in a row, while the sort is to compare each number with other, and compare the smallest or largest one, but it is also the biggest one from a trip. Is it a bit similar? We can see the comments in the for loop, but the meanings of the for loop are different.