Google did not find a decent one (the implementation is too complicated and inefficient), and he wrote one by himself. Post more things in the future, or the blog is very empty! If any of the following improvements can be made, I forgot to tell you.
Sort from bottom to top. For example:
Now we want to sort the following arrays in ascending order.
9 8 7 6 5 4 3 2 1
Step 1 :( Len = 1) 8 9 6 7 4 5 2 3 1
Step 2 :( Len = 2) 6 7 8 9 2 3 4 5 1
Step 3: (LEN = 4) 2 3 4 5 6 7 8 9 1
Step 4: (LEN = 8) 1 2 3 4 5 6 7 8 9
Each merge group is separated by spaces. Len means to merge the adjacent two segments with the length of Len in the array. When Len is greater than the array length, it ends.
So easy! It should be easy to understand. For specific implementation, see the followingCode.
Template <class T, Class C> void msort (T * Table, const Int & size, c cmp) {int flag = 0; T * TMP = new T [size]; T * SRC; T * DST; int b1, b2, E1, E2, Len, index, di; For (LEN = 1; Len <= size; Len * = 2) //! O (logn) {If (flag % 2 = 0) src = table, DST = TMP; else src = TMP, DST = table; For (Index = 0; index <size; index + = (LEN <1 ))//! O (n) {If (index + Len> size) {for (DI = index; Di <size; Di ++) DST [di] = SRC [di]; break;} b1 = index, b2 = index + Len, e1 = b1 + Len, E2 = B2 + Len, DI = index; If (E2> size) E2 = size; while (b1 <E1 & b2 <E2) DST [di ++] = CMP (SRC [B1], Src [B2])? SRC [B1 ++]: SRC [B2 ++]; while (b1 <E1) DST [di ++] = SRC [B1 ++]; while (b2 <E2) DST [di ++] = SRC [B2 ++];} flag ++;} If (flag % 2 = 1) memcpy (table, DST, sizeof (INT) * size); Delete [] TMP ;}
Test code:
Bool CMP (const Int & A, const Int & B) {return a <B;} int main () {int hsize = 20; int Testa [20] = \
{17, 92, 3, 88, 5, 6, 7, 8, 9, 40, 11, 12, 13, 14, 25, 16, 87, 18, 19, 20}; msort (testa, hsize, CMP); For (INT I = 0; I
To be officially used, you should implement the memory distributor by yourself. Don't want to be too complicated. If you call it frequently, directly transfer it to the cache.