Algorithm final solution (3) -- merge and sort
Merge Sorting
O (NlogN), so the worst case of Merge Sorting can reach the average level of fast sorting
Requires additional storage space O (n)
1. Constantly split the data until the remaining one
2. When merging data, it is actually two ordered arrays. Therefore
This process is to merge and sort two sorted arrays.
// Merge Sorting // O (NlogN), so the worst case of Merge Sorting can reach the average level of fast sorting // requires additional storage space O (n) // 1. Continuously split the data until the data is merged one by one // 2. The data is actually two ordered arrays, so // This process is to merge and sort two ordered arrays # include "sort. h "// merge function implements the merging process // I is the minimum index of the array, j is the median value, and k is the maximum index value int merge (void * data, int size, int esize, int I, int k, int j, int (* compare) (const void * key1, const void * key2) {int ipos, jpos, mpos; // I, j, m cursor int * a = (int *) data; int * m; // apply for extra space of m if (m = (int *) malloc (sizeof (int) * size) = NULL) {return-1;} memcpy (m, 0, sizeof (int) * size); ipos = I; jpos = j; // j is the median mpos = 0; while (ipos <= j | jpos <= k) {while (ipos <= j & jpos> = k) // when the remaining I index is not in the middle {memcpy (& m [mpos], & a [ipos], sizeof (int); ipos ++; mpos ++;} while (ipos> = j & jpos <= k) // The j index is not in the middle {memcpy (& m [mpos], & a [jpos], sizeof (int); jpos ++; mpos ++;} if (compare (& a [ipos], & a [jpos]) <= 0) // a small number is first inserted into the m temporary sequence {memcpy (& m [mpos], & a [ipos], sizeof (int); ipos ++; mpos ++;} else {memcpy (& m [mpos], & a [jpos], sizeof (int); jpos ++; mpos ++ ;}} data = m; // return data. At this time, the sorting is completed. free (m); // Finally, the mreturn 0;} // sorting function int mgsort (void * data, int size, int esize, int I, int k, int (* compare) (const void * key1, const void * key2) {int j; if (I <k) {j = (k + I-1)/2; // Let j take the intermediate value if (mgsort (data, size, esize, I, j, compare) <0) // continuously split the left and combine {return-1;} if (mgsort (data, size, esize, j + 1, k, compare) after recursion )) // split the right {return-1;} if (merge (data, size, esize, I, k, j, compare) <0) {return-1 ;}} return 0 ;}