【问题标题】:Whats wrong with my QuickSort implementation?我的快速排序实现有什么问题?
【发布时间】:2014-10-27 10:53:43
【问题描述】:
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 

在最后一种情况下没有正确排序。

谁能帮忙。我被困了这么久。

提前致谢!

【问题讨论】:

  • 为什么会这样? if(a[j] &lt;= a[pivot]) 你正在交换相等的元素。
  • 这听起来像是学习使用调试器的绝佳机会。在最后一个案例中逐步检查您的代码,并亲自查看哪里出了问题。
  • 谢谢马尔科。我现在明白了!
  • 请修正你的缩进。

标签: java quicksort


【解决方案1】:

在这个sn-p:

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

当序列被排序为 1 2 2 4 3 4 5 5 7 6 10 时,枢轴是 '4'(左侧),而比较 4

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2023-01-31
    • 2018-09-20
    • 2021-06-13
    • 2020-06-21
    相关资源
    最近更新 更多