Mergesort)
1,Thoughts:
Multiple times, two or more ordered tables are merged into a new ordered table.
2,Algorithm time complexity
In the best case: a merge operation requires n times and a total of N logstores, so it is O (n * logn)
In the worst case, it is O (n * logn) near the average)
Note: For files with a length of N, logn dual-path merge is required, and the time for each merge is O (n ), therefore, the time complexity is O (nlgn) in both the best and worst cases ).
3,Stability
Merge Sorting is a stable sorting algorithm. In the merge process, the relative position of the elements is not changed.
4. The disadvantage is that it requires extra O (n) space. HoweverIt is suitable for sorting multiple linked lists.
/**
* @ Author Administrator
* Parallel sorting
*/
Public class mergesort {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Int [] DATA = {1, 7, 16, 21, 41, 46, 52 };
Mergesort (data, 0, Data. Length-1 );//
Printdata (data );
}
Private Static void mergesort (INT [] data, int low, int high ){
If (low> = high ){
Return;
}
Int mid = (low + high)/2;
Mergesort (data, low, mid );
Mergesort (data, Mid + 1, high );
Merge (data, low, mid, high );
}
Private Static void merge (INT data [], int low, int mid, int high ){
Int [] temp = new int [High-low + 1];
Int key = 0;
Int I = low;
Int J = Mid + 1;
/** Consider data from low to high as two arrays separated from mid
* Traverse the two arrays separately and put the minimum value into the temporary array.
**/
For (; I <= Mid & J <= high; key ++ ){
If (data [I]> data [J]) {
Temp [Key] = data [J];
J ++;
} Else {
Temp [Key] = data [I];
I ++;
}
}
/** If the traversal is complete from data [low] to data [Mid], the values from data [min + 1] to data [High] may not be completely traversed.
* These values must be larger than data [Mid] and are ordered. You can append them directly to temp */
If (I> mid ){
While (j <= high ){
Temp [Key] = data [J];
Key ++;
J ++;
}
}
/** Likewise */
If (j> high ){
While (I <= mid ){
Temp [Key] = data [I];
Key ++;
I ++;
}
}
/** Return the value of the temp array to the data array */
Setdata (data, temp, low );
}
Private Static void setdata (INT [] data, int [] temp, int low ){
If (data. Length <temp. Length ){
Return;
} Else {
For (INT I = 0; I <temp. length; I ++ ){
Data [Low + I] = temp [I];
}
}
}
Public static void printdata (INT [] data ){
For (int I: Data ){
System. Out. Print (I + "");
}
System. Out. println ();
}
}