在java中快速排序没有正确排序

时间:2013-10-27 19:29:48

标签: java algorithm sorting quicksort

我有这个QuickSort算法,它似乎对给定的输入数组进行排序,但不完全:

public static int partition(int[] A,int low,int high){
    int pivot=A[high-1];
    int i=low-1;
    int temp=0;
    for(int j=low;j<A.length-1;j++){
        if(A[j]<pivot){
            i++;
            temp = A[j];
            A[j]=A[i];
            A[i]=temp;
        }
    }
    temp=A[high-1];
    A[high-1]=A[i+1];
    A[i+1]=temp;
    return i+1;
}

public static void Qsort(int[] A,int low,int high){
    if(low<high){
        int p=partition(A,low,high);
        Qsort(A,low,p-1);
        Qsort(A,p+1,high);
      }
}

我正在调用main中的方法Qsort

Qsort(arr,0,arr.length);

例如,此数组已正确排序

6,5,3,7,1,2

但是这个

{6,5,3,7,1,2,4} is sorted like this {1 3 2 4 5 6 7}

如果我将最后一个索引更改为8而不是4则可以。这令人困惑。 我认为错误很小但我找不到。

感谢您的帮助。

编辑: 解决问题的正确方法:

public static int partition(int[] A,int low,int high){
   int pivot=A[high];
   int i=low;
   int temp=0;
   for(int j=low;j<high;j++){
      if(A[j]<pivot){
         temp = A[j];
         A[j]=A[i];
         A[i]=temp;
         i++;
      }
  }
  temp=A[high];
  A[high]=A[i];
  A[i]=temp;
  return i;
}

主要调用Qsort应该是:(重要的是)

Qsort(arr,0,arr.length-1);

感谢大家的帮助。

1 个答案:

答案 0 :(得分:0)

public static int partition(int[] A,int low,int high){
    int pivotIndex=0;
    int pivot=A[pivotIndex];
    int i=low;    
    int temp=A[pivotIndex];
    A[pivotIndex]=A[high];
    A[high]=temp;
    for(int j=low;j<high;j++){
        if(A[j]<pivot){
            temp = A[j];
            A[j]=A[i];
            A[i]=temp;
            i++;
        }
    }
    temp=A[high-1];
    A[high-1]=A[i+1];
    A[i+1]=temp;
    return i;
}

要使其发挥作用,需要进行一些改进:

  1. 选择枢轴索引不要高-1,为简单起见,我们取0
  2. 在输入for循环之前将元素pivotIndex与high交换
  3. 交换后增加storeIndex i,而不是之前
  4. 返回storeIndex i而不是i ++