Dual Pivot快速排序,按Yaroslavskiy降序排列

时间:2019-10-09 18:18:31

标签: java

我被要求在Java中实现双重枢纽快速排序算法。我的教授还希望该算法按降序对数组进行排序。我写了一个程序来实现算法,但我不知道如何将其更改为降序。这是我的快速排序方法代码:

 public static int[] DualPivotQuickSortYaroslavskiy(int[] A, int left, int right){

    if(right - left >= 1){
      int p = A[left];
      int q = A[right];

      if(p > q){
        //swap p and q
        int temp = p;
        p = q;
        q = temp;
      }
      int l = left + 1;
      int g = right - 1;
      int k = l;
      while(k <= g){
        if(A[k] < p){
          //swap A[k] and A[l]
          int temp = A[k];
          A[k] = A[l];
          A[l] = temp;
          l = l + 1;
        }else{
          if(A[k] > q){
            while(A[g] > q && k < g){
              g = g - 1;
            }
            //swap A[k] and A[g]
            int temp = A[k];
            A[k] = A[g];
            A[g] = temp;
            g = g - 1;
            if(A[k] < p){
              //swap A[k] and A[l]
              temp = A[k];
              A[k] = A[l];
              A[l] = temp;
              l = l + 1;
            }
          }
        }
        k = k + 1;
      }
      l = l - 1;
      g = g + 1;
      //swap A[left] and A[l]
      int temp = A[left];
      A[left] = A[l];
      A[l] = temp;
      //swap A[right] and A[g]
      temp = A[right];
      A[right] = A[g];
      A[g] = temp;

      DualPivotQuickSortYaroslavskiy(A, left, l - 1);
      DualPivotQuickSortYaroslavskiy(A, l + 1, g - 1);
      DualPivotQuickSortYaroslavskiy(A, g + 1, right);

    }//end of if

    return A;
}

0 个答案:

没有答案