谁能看到为什么递归排序示例在第二次调用递归方法后仍继续运行。当第二次通话后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));
}
}
答案 0 :(得分:1)
尽管我没有真正在这里找到完整的逻辑,但是我相信缺少“ return”语句。当控件出现递归方法调用调用时,该方法将再次执行。但是,一旦执行完递归调用,便会继续执行原始方法,然后您会看到意外的行为!
在进行递归调用时也会在其他地方返回(中断执行流),以防止按预期的方式进一步执行代码块
if (low_index < j) {
System.out.println("Running 1");
System.out.println(j + " " + low_index);
quickSort(low_index, j, "Run 1---------");
//recursive code invoked, but prevent the control to process downstream code
return;
}