Exchange method:
The procedures of the exchange method are the clearest and simplest. Each time, the current elements are compared and exchanged with the subsequent elements one by one.
[Cpp]
# Include <iostream. h>
Void ExchangeSort (int * pData, int Count)
{
Int iTemp;
For (int I = 0; I <Count-1; I ++)
{
For (int j = I + 1; j <Count; j ++)
{
If (pData [j] <pData [I])
{
ITemp = pData [I];
PData [I] = pData [j];
PData [j] = iTemp;
}
}
}
}
Void main ()
{
Int data [] = {10, 9, 8, 7, 6, 5, 4 };
ExchangeSort (data, 7 );
For (int I = 0; I <7; I ++)
Cout <data [I] <"";
Cout <"/n ";
}
# Include <iostream. h>
Void ExchangeSort (int * pData, int Count)
{
Int iTemp;
For (int I = 0; I <Count-1; I ++)
{
For (int j = I + 1; j <Count; j ++)
{
If (pData [j] <pData [I])
{
ITemp = pData [I];
PData [I] = pData [j];
PData [j] = iTemp;
}
}
}
}
Void main ()
{
Int data [] = {10, 9, 8, 7, 6, 5, 4 };
ExchangeSort (data, 7 );
For (int I = 0; I <7; I ++)
Cout <data [I] <"";
Cout <"/n ";
}
Before comparison | first time | second time | third time | fourth time | fifth time | sixth time
10 9 8 7 6 5 4
9 10 10 10 10 10 10
8 8 9 9 9 9 9
7 7 7 8 8 8 8
6 6 6 6 7 7 7
5 5 5 5 6 6
4 4 4 4 4 5
From the above algorithm, the efficiency is basically the same as that of the bubble method.
Reverse Order (worst case)
First round: 10, 9, 8, 7-> 9, 10, 8, 7-> 8, 10, 9-> 7, 10, 9, 8 (three exchanges)
Round 2: 7, 10, 9-> 7, 9, 10, 8-> 7, 8, 10, 9 (exchange twice)
First round: 7, 8, 10, 9-> 7, 8, 9, 10 (switching once)
Cycles: 6
Number of exchanges: 6
Others:
First round:,->, (exchange once)
Round 2: 7, 10, 8, 9-> 7, 8, 10, 9-> 7, 8, 10, 9 (exchange once)
First round: 7, 8, 10, 9-> 7, 8, 9, 10 (switching once)
Cycles: 6
Number of exchanges: 3
From the running table, the exchange is almost as bad as the bubble. This is true. The number of loops is also 1/2 * (n-1) * n, so the complexity of the algorithm is still O (n * n ). Because we cannot give all the information, we can only tell you that the exchange is equally bad (in some cases, slightly better, in some cases ).