原理
归并排序主要是采用了分治思想,所谓分治就是把问题分解成一个个的小问题然后递归求解,而治的阶段就是将分的阶段所得的答案修补在一起。
合并子序列
那么治阶段的倒数第二步是怎么实现的呢?来看下面的步骤。
首先是对比俩个子序列的第一个元素,将小的放在临时的数组当中。图中是1 < 4,因此将1放入临时数组中。
再继续对比剩下的元素,图中2 < 4,因此将2放入临时数组中。
此时,3 < 4因此还是将3放入临时数组中。接下来一直执行这个操作。最后,如果一个子序列已经全部插入临时数组中后。我们需要将另一个子序列按顺序插入临时数组。最后需要将临时数组中的元素按顺序放入原数组中。
代码实现
public static void main(String[] args) {
int[] array = {8,4,5,7,1,3,6,2};
int[] temp = new int[array.length];
merge(array,0,array.length - 1,temp);
System.out.println(Arrays.toString(array));
}
public static void merge(int[] arr,int left,int right,int[] temp){
if (left < right){
int mid = (left + right) / 2;
merge(arr,left,mid,temp);
merge(arr,mid + 1,right,temp);
mergeSort(arr,left,mid,right,temp);
}
}
public static void mergeSort(int[] array,int left,int mid,int right,int[] temp){
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right){
if (array[i] < array[j]){
temp[t] = array[i];
t++;
i++;
}else {
temp[t] = array[j];
t++;
j++;
}
}
//如果左边子序列有剩余
while (i <= mid){
temp[t] = array[i];
t++;
i++;
}
//如果右边子序列有剩余
while (j <= right){
temp[t] = array[j];
t++;
j++;
}
//最后将临时数组中的元素按顺序放入原数组
t = 0;
int tempLeft = left;
while (tempLeft <= right){
array[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
声明
本文是作者在学习数据结构中的一些笔记,希望能够帮助到大家。作者才疏学浅,如有错误,欢迎批评指正。