Original address: C/C ++ algorithm learning notes (5)-Selection Method
Selection Method:
Now we can finally see the hope: This method improves the performance (in some cases). This method is similar to our human sorting habits:
Select the smallest value exchange from the data and the second value exchange from the saved part.
# Include <iostream. h> void selectsort (int * pdata, int count) {int itemp; int IPOs; For (INT I = 0; I <count-1; I ++) {itemp = pdata [I]; IPOs = I; for (Int J = I + 1; j <count; j ++) {If (pdata [J] <itemp) {itemp = pdata [J]; IPOs = J ;}} pdata [IPOs] = pdata [I]; pdata [I] = itemp ;}} void main () {int data [] = {10, 9, 8, 7, 6, 5, 4}; selectsort (data, 7); For (INT I = 0; I <7; I ++) cout <data [I] <"; cout <"/N ";}the following figure shows the sorting method. When I = 0: itemp = pdata [0] = 10; IPOs = I = 0; j = 1; pdata [J] <itemp ---> pdata [1] = 9 <10; itemp = pdata [1] = 9; IPOs = j = 1; j ++ = 2 J = 2; pdata [J] <itemp ----> pdata [2] = 8 <9; itemp = pdata [2] = 8; IPOs = J = 2; j ++ = 3... j = 6; pdata [J] <itemp ----> pdata [6] = 4 <5; itemp = pdata [6] = 4; IPOs = J = 6; j ++ = 7; pdata [6] = pdata [0]; pdata [0] = 4;
Before comparison | first time | second time | third time
10 4 4 4
9 9 5 5
8 8 8 6
7 7 7 7
6 6 6 8
5 5 9 9
4 10 10 10
From the above, we can see that the selection of sorting method does not exchange data at the beginning, but compares it with all the data with the first data,
If the first data is smaller than the second data, put the second data in a temporary variable and record the smaller data.
The position of the data in the set to be sorted. Use the next data in the set to compare it with the data we previously placed in the temporary variable.
That is, we currently think that the minimum data comparison is smaller than the data we have selected before, then replace this variable. If
If the data is large, the next data is used for comparison. We know that all the data has been compared. In this case, the Temporary Variable accesses
The smallest data. We swap the data with the first one. At this point, the smallest element is ranked first.
Reverse Order (worst case)
First round:,-> (itemp = 9),-> (itemp = 8),-> (itemp = 7, 8, 10 (exchange once)
Round 2:,->, (itemp = 8)-> (itemp = 8), 8, 9, 10 (exchange once)
First round:,-> (itemp = 9), (0 switching)
Cycles: 6
Number of exchanges: 2
Others:
Round 1:,-> (itemp = 8),-> (itemp = 7),-> (itemp = 7), 10, 8, 9 (exchange once)
Round 2:,-> (itemp = 8),-> (itemp = 8), (exchange once)
First round:,-> (itemp = 9), (exchange once)
Cycles: 6
Number of exchanges: 3
Unfortunately, the number of loops required by the algorithm is still 1/2 * (n-1) * n. Therefore, the algorithm complexity is O (n * n ).
Let's look at his exchange. Each outer loop generates only one exchange (only one minimum value ). So F (n) <= N
So we have f (n) = O (n ). Therefore, when data is messy, it can reduce the number of exchanges.