Quicksort不排序长度为2的数组

时间:2015-03-25 12:12:58

标签: java sorting quicksort

我正在尝试实现quicksort的一部分,我调用一个名为splitPoint的方法。 SplitPoint将使用数组的第一个索引作为透视值,并且数据透视图将移动到数组的中心。它将返回pivot的新索引的索引。但是,如果我有一个长度为2的数组并且它正在降序,例如[2,1],则无法排序。该方法适用于其他所有方法。我认为,如果这不起作用,我的快速通道将无法正常工作。

 public int splitPoint(int[] a, int first, int last){

    int splitPoint = a[first];
    int low = first + 1;
    int high = last - 1;

    int temp; //holds the temp val for swapping values

    while(low < high){
        while(a[low] <= splitPoint && low != last && high > low){    
            low++;  
            //System.out.println("While loop 1 tracer");
            }
        while(a[high] > splitPoint && high >= first && high >= low){
            high--;
            //System.out.println("While loop 2 tracer");
        }

        if(low <= high){
            temp = a[low];
            a[low] = a[high];
            a[high] = temp;
            low++;
            high++;
        }

        System.out.println(Arrays.toString(a)); // tracer

    }

    a[first] = a[high];
    a[high] = splitPoint;

    return high;
}

2 个答案:

答案 0 :(得分:0)

简单回答是完成代码。

假设您的通话如下:

splitPoint({2,1},0,1);

int splitPoint = a[first];  // Will hold a value of 2.
int low = first + 1;   //low = 0 + 1 = 1.
int high = last - 1;  // high = 1 - 1 = 0.

int temp; //holds the temp val for swapping values

while(low < high)  //<== here. low = 1.  high = 0.  low > high, test is false--loop is NOT performed.

a[first] = a[high];  // a[0] = a[0] = 2.
a[high] = splitPoint;  //a[0] = 2

return high;  //returns 0.

因此,简而言之,您的问题在于初始化为低和高。

答案 1 :(得分:0)

如果你检查,你会看到输入如[5,0,3],它会返回[0,5,3]。因此,即使对于较大的阵列也存在问题。

稍微修改后的代码版本应该可以正常工作:

static int split(int[] array, final int first, final int last) {
    int low = first;
    int high = last;

    int splitPoint = first;
    while (low < high) {
        while (array[high] > array[low] && high > low) {
            high--;
        }
        while (array[low] <= array[high] && high > low) {
            low++;
        }
        if (low < high) {
            int tmp = array[low];
            array[low] = array[high];
            array[high] = tmp;
            if (low == splitPoint) {
                low++;
                splitPoint = high;
            } else {
                high--;
                splitPoint = low;
            }
        }
    }
    return splitPoint;
}

示例:

public static void main(String[] args) {
    int[] array = new int[]{5, 0, 3};
    System.out.println(split(array, 0, array.length - 1));
    System.out.println(Arrays.toString(array));
}

输出:

2
[3, 0, 5]