public static void quickSort(int[] a, int begin, int end, String s) {
int i = begin, j = end;
int middle = begin + (end - begin) / 2;
int pivot = a[middle];
while (i <= j) {
while (a[i] < pivot) {
i++;
quickSortComparisons++;
}
while (a[j] > pivot) {
j--;
quickSortComparisons++;
}
if (i <= j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
quickSortExchanges++;
i++;
j--;
}
}
// recursively sort two sub parts
if (begin < j)
quickSort(a, begin, j, s);
if (end > i)
quickSort(a, i, end, s);
quickSortWork = quickSortComparisons + (3 * quickSortExchanges);
// WANT TO DO SOMETHING HERE WHEN THE ARRAY
//IS COMPLETELY SORTED AND ALL RECURSIVE CALLS ARE FINISHED.
}
我正在尝试实现quickSort功能。它排序正确,但我遇到的问题是,当数组完全排序时,我需要打印一些东西。因为这是递归调用的,如果我只是在最后打印,它会在每次调用函数时被打印出来。我可以创建一些类型的虚拟基础案例,可能是这样的:
if(!sorted){ //do all quicksort operations}
else{ //print values I wish to print}
答案 0 :(得分:0)
您应该将初始调用包装在非递归函数中,如下所示:
public static void quickSort(int[] a, int begin, int end, String s) {
// Call the recursive method
quickSort0(a, begin, end, s);
// When you get here, the array is sorted
System.out.println("Sorted array: " + Arrays.toString(a));
}
private static void quickSort0(int[] a, int begin, int end, String s) {
// Your original, recursive quickSort method
}