Merge sort algorithm analysis
1. Algorithmic thinking
Using the idea of divide and conquer, the original array is divided into two parts each time, and then the sub-arrays are sorted, and finally the sorted arrays are merged to form a new ordered sequence.
1.1 Execution process
2. Implementation steps
2.1 mergeSort() method
public static void mergeSort(int[]arr){
if (arr == null || arr.length < 2){
return;
}
mergeSort(arr,0,arr.length-1);
}
2.2 Split into several subarrays
public static void mergeSort(int[] arr, int l, int r) {
//如果l和r相等,说明中间只有一个数,数组已经排好序了。
if (l == r) {
return;
}
int mid = l + ((r - l) >> 1);//求中点
//l到mid之间变为有序的
mergeSort(arr, l, mid);
//mid+1到r之间变成有序的
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
2.3 Merge subarrays
public static void merge(int[] arr ,int l ,int m ,int r){
//辅助数组长度的大小
int[] help = new int[r - l + 1];
int i = 0;//辅助数组指针
int p1 = l;//左边数组指针
int p2 = m + 1;//右边数组指针
while (p1 <= m && p2 <= r) {
help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
// 有一边结束了就输入另一边
while (p1 <= m) {
help[i++] = arr[p1++];
}
while (p2 <= r) {
help[i++] = arr[p2++];
}
for (i = 0; i < help.length; i++) {
arr[l + i] = help[i];
}
}
3. Time complexity analysis
Use Master's formula to analyze the time complexity of recursive behavior
The comparison formula is: T(N) = 2 T(N/2) + O(N); *
So the time complexity is O(N * log N);