※归并排序(merge sort)

/**

  • 归并排序:通常以递归的方式来实现,它反复将所处理的数组分成两半,并分别对这两半进行排序, 最后再把经过排序的数组归并在一起。
    */
    归并排序的伪代码实现:
    将数组分为两半
    对左半部分排序
    对右半部分排序
    合并左右两部分

合并算法的伪代码描述:
i1 = 0; //左半部分的索引
i2 = 0;//右半部分的索引
for(数组中元素的个数){
if(左半部分下标为i1的元素值<= 右半部分下标为i2的元素值){
将左半部分的当前值保存到新数组
i1++;
}else{
将右半部分的当前值保存到新数组
i2++;
}
-----------------------------------------------------------------------------------------------------------
//代码实现:
public static void mergeSort(int[] num) {
// 将数组分为两半
int[] left = Arrays.copyOfRange(num, 0, num.length / 2);// 不包括终点元素
int[] right = Arrays.copyOfRange(num, num.length / 2, num.length);
if (left.length > 1) {
mergeSort(left);
mergeSort(right);
merge(num, left, right);
}
}

public static void merge(int[] result, int[] left, int[] right) {
int i1 = 0; // index of left array
int i2 = 0; // index of right array
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length || (i1 < left.length && left[i1] <= right[i2])) {
result[i] = left[i1]; // take from left
i1++;
} else {
result[i] = right[i2]; // take from right
i2++;
}
}
}

////end

原文地址:https://www.cnblogs.com/understander/p/6686360.html