【发布时间】:2019-10-23 23:58:08
【问题描述】:
谁能明白为什么这个排序递归的例子在第二次调用递归方法后继续运行。当i == high_index 在第二次调用之后它们都是2 时,出于某种原因,我在互联网上找到的这段代码再次运行同一行,但有一些奇怪的i=4 和high_index=6 值。我只是看不到错误。所有的递归都应该在第二次之后停止,并且应该对数组进行排序。
查看注释//WHY DOES THIS LINE RUN TWICE IN A ROW WITH DIFFERENT VALUES?????的行
package dataClass;
import java.util.Arrays;
public class QuickSort {
private int temp_array[];
private int len;
public void sort(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
this.temp_array = nums;
len = nums.length;
quickSort(0, len - 1, "First");
//System.out.println("what");
}
private void quickSort(int low_index, int high_index, String one_two) {
System.out.println("***" + low_index + " " + high_index);
System.out.println(one_two);
int i = low_index;
int j = high_index;
// calculate pivot number
int pivot = temp_array[low_index+(high_index-low_index)/2];
// Divide into two arrays
System.out.println(Arrays.toString(temp_array));
while (i <= j) {
while (temp_array[i] < pivot) {
System.out.println("This happens");
i++;
}
while (temp_array[j] > pivot) {
System.out.println("Or this happens");
j--;
}
if (i <= j) {
System.out.println("Execute");
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
System.out.println("i=" + i + " high_index=" + high_index);
}
}
// call quickSort() method recursively
if (low_index < j) {
System.out.println("Running 1");
System.out.println(j + " " + low_index);
quickSort(low_index, j, "Run 1---------");
}
System.out.println("**i=" + i + " **high_index=" + high_index); // WHY DOES THIS LINE RUN TWICE IN A ROW WITH DIFFERENT VALUES?????
System.out.println("Why run again without call to quickSort()?");
if (i < high_index) {
System.out.println("Running 2");
System.out.println(i + " " + high_index);
quickSort(i, high_index, "Run 2---------");
}
}
private void exchangeNumbers(int i, int j) {
int temp = temp_array[i];
temp_array[i] = temp_array[j];
temp_array[j] = temp;
}
// Method to test above
public static void main(String args[])
{
QuickSort ob = new QuickSort();
int nums[] = {7, -5, 3, 2, 1, 0, 45};
System.out.println("Original Array:");
System.out.println(Arrays.toString(nums));
ob.sort(nums);
System.out.println("Sorted Array");
System.out.println(Arrays.toString(nums));
}
}
【问题讨论】:
-
使用调试器逐步完成它,所有内容都会显示出来。提示:想象在第一个条件块中进行了递归调用,并且在该调用中没有调用第二个条件块? 1) 在递归调用中打印的最后一件事是什么? 2) 从递归调用返回后会立即发生什么?
-
ahh 现在给出的答案是有意义的,它运行对初始方法的第一次调用并继续,实际上它使用 i、j、low 和高指数。谢谢