public class mergeSort {
public static void merge(int[] a
, int left
, int mid
, int right
) {
int[] tmp
= new int[a
.length
];
int p1
= left
, p2
= mid
+ 1, k
= left
;
while (p1
<= mid
&& p2
<= right
) {
if (a
[p1
] <= a
[p2
])
tmp
[k
++] = a
[p1
++];
else
tmp
[k
++] = a
[p2
++];
}
while (p1
<= mid
) tmp
[k
++] = a
[p1
++];
while (p2
<= right
) tmp
[k
++] = a
[p2
++];
for (int i
= left
; i
<= right
; i
++)
a
[i
] = tmp
[i
];
}
public static void mergeSort(int[] a
, int start
, int end
) {
if (start
< end
) {
int mid
= (start
+ end
) / 2;
mergeSort(a
, start
, mid
);
mergeSort(a
, mid
+ 1, end
);
merge(a
, start
, mid
, end
);
}
}
}
归并排序比较简单,中心思想就是分治,使用递归将模块一直拆分,这里是二路归并排序,所以只需要拆分为两块,递归结束的条件是不可再分,也就是分为一个的时候停止,从第一个开始时将每一个模块当作一个已经排序好的数组,有如双指针,在两个数组头设立指针,进行值的比较,然后插入到新数组中。
转载请注明原文地址:https://tech.qufami.com/read-5965.html