数组:4,1,5,8,2,6,9,7,11,3

public static void quickSort(int arr[], int low, int high) {
    System.out.pr,java,if-statement,recursion,while-loop,quicksort"/>
	














首页 > 解决方案 > if v/s while: 对于这段代码,如果我正在使用 while 循环,它会继续无限循环,但是当使用 "if(low

数组:4,1,5,8,2,6,9,7,11,3

public static void quickSort(int arr[], int low, int high) {
    System.out.pr

问题描述

数组:4,1,5,8,2,6,9,7,11,3

public static void quickSort(int arr[], int low, int high) {
    System.out.println(low + " " + high);
    while(low < high) {
        int mid = quickPart(arr, low, high);            
        quickSort(arr, low, mid - 1);          
        quickSort(arr, mid + 1, high);
    }
}

它正在打印:0 0 然后 2 1,然后再打印 0 0 和 2 1 等等,对于Sopl(low + " " + high)

但对于..

public static void quickSort(int arr[], int low, int high) {
    System.out.println(low + " " + high);
    if(low < high) {
        int mid = quickPart(arr, low, high);            
        quickSort(arr, low, mid - 1);          
        quickSort(arr, mid + 1, high);
    }
}

它正在打印:0 9, 0 1, 0 0, 2 1, 3 9, 3 3, 5 9... 工作正常。

分区代码,如果有帮助的话..

public static int quickPart(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for(int j = low; j < high; j++) {
        if(pivot > arr[j]) {
            i++;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    int temp = arr[i+1];
    arr[i+1] = arr[high];
    arr[high] = temp;
    System.out.println(i++);
    return i+1;
}

对于 if 语句,代码将在low >= high时终止,并且直到 9,即 9 > 9 终止,但对于while + 分区算法,它会重复打印 1。为什么会这样?


您的方法不会更改 and 的值lowhigh因此循环的条件 -(low < high)永远不会为真(循环将立即结束)或始终为真(循环将是无限的)。

这是一种递归算法,因此您不需要循环。您只需要一个if语句来确定递归应该继续还是结束。

标签: javaif-statementrecursionwhile-loopquicksort

解决方案


您的方法不会更改 and 的值lowhigh因此循环的条件 -(low < high)永远不会为真(循环将立即结束)或始终为真(循环将是无限的)。

这是一种递归算法,因此您不需要循环。您只需要一个if确定递归是继续还是结束的语句。


推荐阅读