-1
在下面的代碼中,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++;
}
}
}
}
步驟通過與調試你的代碼。 –