First, the moving map presentation
Second, the idea of analysis
Merge sort is obtained recursively recursive half the original array separated, can not be divided until after (only one element), beginning from the smallest up merge sort array
1. merge sort up time required to sort a temporary array,
2. The merger of the two arrays to be started from a relatively small scratch into an array of pointers move backward,
3. An array until empty, then, do not judge which of the array is empty, the two arrays directly added to the remaining elements of the temporary array,
4. Turn the sorted temporary array element of the array into the original, a synthesis of two arrays, this trip ends.
The idea of the analysis, each pass execution flow as shown below:
Third, the negative heteroaryl analysis
1. Time Complexity: The time complexity of the algorithm recursive formula: T [n] = aT [n / b] + f (n)
Regardless of whether the original array is ordered, must be separated from the recursive and merge sort, it is always time complexity O (nlog2n)
2. Space complexity:
Each time two array merge sort, will use a length n as an auxiliary array for storing an array of combined sequences, the spatial complexity is O (n)
import java.util.Arrays;
{the Main class public
public static void main (String [] args) {
int [] = ARR new new int [] {3,6,4,7,5,2};
Merge (ARR, 0,. 1-arr.length) ;
System.out.println (of Arrays.toString (ARR));
}
// merge
public static void Merge (int [] ARR, Low int, int High) {
int = Center (High + Low) / 2;
IF (Low <High) {
// recursive, until low == high, that is, the array can no longer be divided,
Merge (ARR, Low, Center);
Merge (ARR,. 1 + Center, High);
// arrays can not be divided when start merge sort
mergesort (ARR, Low, Center, High);
System.out.println (of Arrays.toString (ARR));
}
}
// Sort
static void mergesort public (int [] ARR, Low int, int Center, High int) {
// array for temporarily storing the sorted temporary array,
int [] = tempArr new new int [arr.length];
int I = Low , J = Center +. 1;
// temporary array subscript
int index = 0;
// loop through two arrays of numbers, the small insertion into a temporary array
while (i <= center && j = high <) {
// left small number array, a new array is inserted into the
IF (ARR [I] <ARR [J]) {
tempArr [index] = ARR [I];
I ++;
} // the else {small number of the right array, inserted into new array
tempArr [index] = ARR [J];
J ++;
}
index ++;
}
// process the left half of the array redundant data, the left half of the back of redundant data directly added temporary array
the while (I <= Center) {
tempArr [index] = ARR [I];
I ++;
index ++;
}
// process the right half of the array redundant data, the rear right half of redundant data directly added temporary array
while (j < = High) {
tempArr [index] = ARR [J];
J ++;
index ++;
}
// the data in the temporary array back into the original array
for (int K = 0; K <index; K ++) {
ARR [K + Low] = tempArr [K];
}
}
}