合并数组子方法的伪代码:
数组A[p..q] and A[q+1..r];total number is (r - p +1).
MERGE(A, p, q, r)
n1 = q - p + 1
n2 = r - q
let L[1..n1 + 1] and R[1..n2 + 1] be new arrays
for i = 1 to n1
L[i] = A[p + i -1]
for j = 1 to n2
R[j] = A[q + j]
L[n1 + 1] = infinity //flag
R[n2 + 1] = infinity //flag
i = 1
j = 1
for k = p to r
ifL[i] <= R[j]
A[k] = L[i]
i = i + 1
else
A[k] = R[j]
j = j + 1
归并排序算法的伪代码:
MERGESORT(A, p, r)
if p < r
q = (p + r)/2 //向下取整
MERGESORT(A,p,q)
MERGESORT(A,q+1,r)
MERGE(A,p,q,r)
归并排序java代码:
package mergeSort;
/**
* @Author: Wang
* @Date:Created in 23:21 2020/3/15
* @Modify By:
*/
public class MergeSort {
public static void main(String[] args) {
int[] nums =new int[]{20,10,45,32,15,89,96,102};
mergeSort(nums, 0, nums.length - 1);
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
private static void mergeSort(int[] nums, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(nums, p, q);
mergeSort(nums, q + 1, r);
merge(nums,p,q,r);
}
}
private static void merge(int[] nums, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int[] L1 = new int[n1 + 1];
int[] L2 = new int[n2 + 1];
for (int i = 0; i < n1; i++) {
L1[i] = nums[p + i];
}
L1[n1] = Integer.MAX_VALUE;
L2[n2] = Integer.MAX_VALUE;
for (int j = 0; j < n2; j++) {
L2[j] = nums[q + j + 1];
}
int i = 0;
int j = 0;
for (int k = p; k <= r; k++) {
if (L1[i] <= L2[j] && i < n1 ) {
nums[k] = L1[i];
i++;
} else if (j < n2){
nums[k] = L2[j];
j++;
}
}
}
}