Original address: C/C ++ algorithm learning notes (4)-Exchange Method
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.
#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 10
8
9
9 9 9 9
7 7 7 8 8 8 8
6 6 6 6
7 7 7
5 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 ).