From: http://www.cnblogs.com/architect/archive/2009/05/06/1450489.html
// Merge and sort
// Updated by zivsoft at 05/06/2009
Int * Merge (int * a, int alength, int * B, int blength ){
// Merge result pointer
Int * result;
// Initialization result pointer
Result = new int [alength + blength];
Int I = 0, j = 0, K = 0;
// Define the left pointer
A = new int [alength];
// Define the right pointer
B = new int [blength];
// Sort elements and compare between left and right
While (I <alength & J <blength ){
If (A [I] <B [J]) {// The left element is smaller than the right element.
Result [k ++] = A [I ++]; // assign a small value to the result.
}
Else {// The left element is greater than the right element
Result [k ++] = B [J ++]; // assign a small value to the result.
}
}
While (I <alength) {// assign the last element to the result
Result [k ++] = A [I ++];
}
While (j <blength) {// assign the last element to the result
Result [k ++] = B [J ++];
}
Return result;
}
// Merge and sort data into shards
// Updated by zivsoft at 05/06/2009
Int * Split (int * data, int length ){
Int I = 0, j = 0, K = 0;
Int * left, * right, * result;
// Obtain the intermediate subscript
Int middle = length/2;
Left = new int [Middle];
Right = new int [Middle];
// Initialize an ordered result Array
Result = new int [length];
// If the array has only one element, it is returned directly without sorting.
If (length <= 1 ){
Return data;
}
Int rightlength = 0;
// If there are an odd number of elements, the right array length will be re-allocated.
If (length % 2! = 0 ){
Delete [] right;
Rightlength = middle + 1;
Right = new int [rightlength];
}
// Split the Array
For (k = 0; k <length; k ++ ){
If (I <middle ){
Left [I ++] = data [k];
}
Else {
Right [J ++] = data [k];
}
}
Left = Split (left, I); // recursively splits the left array.
Right = Split (right, rightlength); // recursively splits the right Array
Result = Merge (left, I, right, rightlength); // sort and merge
// Printarray (result, k); // output for Lihua (zorywa) side (zivsoft)
Return result;
}