简体   繁体   English

我的QuickSort实施有什么问题?

[英]Whats wrong with my QuickSort implementation?

class PartitionIt
 {
      public static void partitionIt(int[] a, int l, int r, int pivot)
    {
    int i,j;
    i = j = l+1;

    while(j<= r)
    {
        if(a[j] <= a[pivot])
        {
            swap(a,j,i);
            i++;
        }   
        j++;
    }
    swap(a,pivot,--i);
}

public static void swap(int[] a, int j, int i)
{
    int temp = a[j];
    a[j] = a[i];
    a[i] = temp;
}

public static void displayArray(int[] a)
{
    for(int i:a)
        System.out.print(i+" ");
    System.out.println();
}

public static void QuickSort(int[] a, int l, int r)
{
    if(r <= l)
        return;
    int pivot = getPivot(a,l,r);
    partitionIt(a,l,r,pivot);
    QuickSort(a,l,pivot);
    QuickSort(a,pivot+1,r);
}

public static int getPivot(int[] a,int l,int r)
{
    return l;
}

public static void main(String[] args)
{

    int[] a = {3,2,8,5,1,4,7,6};
    int[] b = {1,2,3,4,5,6,7,8,9,0};
    int[] c = {5,4,2,4,7,6,5,3,2,1,10};

    displayArray(a);
    System.out.println("After Parititon with pivot 3");
    QuickSort(a,0,a.length-1);
    displayArray(a);
    System.out.println();

    displayArray(b);
    System.out.println("After Parititon with pivot 1");
    QuickSort(b,0,b.length-1);
    displayArray(b);
    System.out.println();

    displayArray(c);
    System.out.println("After Parititon with pivot 5");
    QuickSort(c,0,c.length-1);
    displayArray(c);
    System.out.println();


}

} }

3 2 8 5 1 4 7 6 
After Parititon with pivot 3
1 2 3 4 5 6 7 8 

1 2 3 4 5 6 7 8 9 0 
After Parititon with pivot 1
0 1 2 3 4 5 6 7 8 9 

5 4 2 4 7 6 5 3 2 1 10 
After Parititon with pivot 5
1 2 2 4 3 4 5 5 6 7 10 

It is not sorting properly in last case. 在最后一种情况下无法正确排序。

Can anyone help here. 任何人都可以在这里帮忙。 I m stuck from so long. 我被困了这么久。

Thanks in advance! 提前致谢!

At This snippet: 在此代码段中:

if(a[j] <= a[pivot])
        {
            swap(a,j,i);
            i++;
        }

The '<=' should be '<'. “ <=”应为“ <”。

while the sequence was sorted to 1 2 2 4 3 4 5 5 7 6 10,the pivot is '4'(the left one),while compare 4 <= 4,i++, this cause the swap(a,pivot,--i) change the location of '4'(the right one ) to '4'(the left one),rather than change the '3' to '4'. 当序列排序为1 2 2 4 3 4 5 5 7 6 10时,枢轴为'4'(左侧),而比较4 <= 4,i ++,这导致swap(a,pivot,- i)将“ 4”(右一个)的位置更改为“ 4”(左一个),而不是将“ 3”的位置更改为“ 4”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM