在下面的代码中,merge()
函数只被调用了两次,然后它进入了一些无限循环。
package Prac;
public class MergeSort {
private static int[] arr = {12, 10, 5, 2, 7, 56, 81, 17, 14, 1 };
private static int[] helper;
public static void main(String[] args) {
MergeSort ob = new MergeSort();
ob.sort();
for (int i : arr) {
System.out.println(arr[i]);
}
}
private void sort() {
int number = arr.length;
helper = new int[number];
mergeSort(0, number - 1);
}
private void mergeSort(int low, int high) {
if (low < high) {
int middle = (low + (high - low)) / 2;
mergeSort(low, middle);
mergeSort(middle + 1, high);
merge(low, middle, high);
}
}
private void merge(int low, int middle, int high) {
for (int i = low; i <= high; i++) {
helper[i] = arr[i];
}
int firstPointer = low;
int secondPointer = middle + 1;
int insertPointer = low;
while (firstPointer <= middle && secondPointer <= high) {
if (helper[firstPointer] < helper[secondPointer]) {
arr[insertPointer] = helper[firstPointer];
firstPointer++;
} else {
arr[insertPointer] = helper[secondPointer];
secondPointer++;
}
insertPointer++;
}
if (firstPointer < middle || middle == 0) {
while (firstPointer <= middle) {
arr[insertPointer] = helper[firstPointer];
firstPointer++;
insertPointer++;
}
} else {
while (secondPointer <= high) {
arr[insertPointer] = helper[secondPointer];
secondPointer++;
insertPointer++;
}
}
}
}