We all knowC ++ sortingThere are four common methods: insert sorting, Hill sorting, exchange sorting, and select sorting. In the previous two articles, we introduced the two sorting methods C ++-insert sorting and Hill sorting. This article introduces the third method of C ++ sorting --Exchange sorting. This series of articles test programs in a unified manner)
Exchange sorting
The basic idea is: Compare the key codes of the records to be sorted in two pairs. If the reverse order occurs, the key codes are exchanged until all objects are sorted.
Bubble Sorting
Bubble Sorting is two adjacent records, which are exchanged in reverse order. This method leads to a small key code floating layer by layer, hence the name. The 51cto forum once discussed whether "Bubble" and "Bubble" are a thing. It seems that this is a translation fault. The English names are both Bubble Sort. You can arrange them when writing them, you can also move it backwards. (The strict version is from back to front, and the Yin version is from back to back. Fortunately, both books are translated as "Bubble Sorting ", otherwise, it is just like some people come to the conclusion that one is from the back to the front, and the other is from the back to the back)
- template <class T>
- void BubbleSort(T a[], int N, int& KCN, int& RMN)
- {
- KCN = 0; RMN = 0; bool exchange = true;
- for (int i = 1; i < N && exchange; i++)
- for (int j = N - 1; j >= i; j--)
- {
- exchange = false;
- if (++KCN && a[j - 1] > a[j]) { swap(a[j - 1], a[j]); exchange = true; RMN += 3; }
- }
- }
Note that you should not write it as follows, although the result is correct:
- template <class T>
- void BubbleSort2(T a[], int N)
- {
- for (int i = 0; i < N; i++)
- for (int j = 1; j < N - i; j++)
- if (a[j - 1] > a[j]) swap(a[j - 1], a[j]);
- }
Test results:
- Sort ascending N=10000 TimeSpared: 0ms
- KCN=9999 KCN/N=0.9999 KCN/N^2=9.999e-005 KCN/NlogN=0.07525
- RMN=0 RMN/N=0 RMN/N^2=0 RMN/NlogN=0
- Sort randomness N=10000 TimeSpared: 1161ms
- KCN=45409094 KCN/N=4540.91 KCN/N^2=0.454091 KCN/NlogN=341.737
- RMN=71526984 RMN/N=7152.7 RMN/N^2=0.71527 RMN/NlogN=538.294
- Sort descending N=10000 TimeSpared: 1022ms
- KCN=49995000 KCN/N=4999.5 KCN/N^2=0.49995 KCN/NlogN=376.25
- RMN=149985000 RMN/N=14998.5 RMN/N^2=1.49985 RMN/NlogN=1128.75
It can be seen that the efficiency is very poor and it is not as good as direct insertion and sorting. I really don't know why people talk about it. Is it to understand fast sorting? Another interesting phenomenon is that, although the reverse-order KCN and RMN are more chaotic, the reverse-order takes less time than the reverse-order. Here we can see the role of the CPU pipeline, here we can give a signal that a real algorithm needs to make full use of the hardware features. When increasing the number of records (N = 1000000), we can see that in the case of full order, blister is better than direct insertion, because at this time there is no need to move the record.