合并排序是一种分而治之的算法,因为该算法会将原始数组拆分为较小的逻辑部分。 可以利用循环或递归来实现该算法。 这两个不同的阶段是分裂阶段,其次是合并阶段。
分裂阶段:将数组分为两个未排序的数组。 将每个拆分数组连续拆分为较小的数组,直到仅存在多个单个元素数组。 单元素数组被排序,因为它们中只有一个元素。
合并阶段:现在,每个单个元素数组都合并回到更大的数组中。 在合并阶段,将两个数组合并,以便在新的较大排序数组中对元素进行排序。 重复此过程,直到剩下单个排序数组为止。 这不是就地算法,因为使用了临时数组。
Algorithm Classification
下表包含有关合并排序算法分析的信息。 它根据时间复杂度以及空间复杂度定义了最坏,平均和最佳情况。
Please use the following link for an explanation on Big-O notation and what is good, fair and bad.
Merge Sort In Java
public final class MergeSort {
public void sort(int[] collection) {
if (collection != null) {
mergeSort(collection, 0 , collection.length);
} else {
throw new IllegalArgumentException("Input paramenter for array to sort is null.");
}
}
public void mergeSort(int[] collection, int minIndex, int maxIndex) {
if (maxIndex - minIndex < 2) {
return;
}
int centre = (minIndex + maxIndex) / 2;
mergeSort(collection, minIndex, centre);
mergeSort(collection, centre, maxIndex);
mergeBack(collection, minIndex, centre, maxIndex);
}
public void mergeBack(int[] collection, int minIndex, int centre, int maxIndex) {
if (collection[centre - 1] <= collection[centre]) {
return;
}
int tempMinIndex = minIndex;
int tempCentre = centre;
int tempIndex = 0;
int[] tempArray = new int[maxIndex - minIndex];
while ((tempMinIndex < centre) && (tempCentre < maxIndex)) {
if(collection[tempMinIndex] <= collection[tempCentre]) {
tempArray[tempIndex++] = collection[tempMinIndex++];
} else {
tempArray[tempIndex++] = collection[tempCentre++];
}
}
System.arraycopy(collection, tempMinIndex, collection, minIndex + tempIndex, centre - tempMinIndex);
System.arraycopy(tempArray, 0, collection, minIndex, tempIndex);
}
}
Sample Code (GitHub)
可以在此处查看MergeSort类的详细信息。 可以在此处查看MergeSort JUnit Test类的详细信息。
Conclusion
合并排序算法构成较大的一组排序算法的一部分。 通过经验学习是我创建这篇关于Java合并排序算法实现的帖子的原因。 我了解了很多其他人如何解决其他语言(包括Java中的不同实现)的合并排序算法的知识。
The post Merge Sort Algorithm in Java appeared first on Code2Bits.