在QuickSort的数组分区中出错

时间:2015-01-11 15:58:06

标签: java quicksort indexoutofboundsexception

我正在尝试按照快速排序算法对数组进行分区,但在尝试这样做时会得到奇怪的输出。以下是代码。

输入数组

 int[] newArray = {24, 26, 8, 6, 14, 33, 21, 19};
 partitionArray(newArray, -1, newArray.length - 1);

分区方法

private static int partitionArray(int[] array, int leftPointer, int rightPointer) {

  int pivot = rightPointer;
  while (leftPointer < rightPointer) {

      System.out.println("leftPointer: " + leftPointer + " rightPointer: " + rightPointer);

      while (array[++leftPointer] <= array[pivot] && leftPointer < rightPointer);
      while (array[--rightPointer] > array[pivot] && rightPointer > leftPointer);

      System.out.println("leftPointer2: " + leftPointer + " rightPointer2: " + rightPointer);

      if (leftPointer < rightPointer) {
          swapElements(array, leftPointer, rightPointer);
      }
  }
    swapElements(array, leftPointer, pivot);
    return leftPointer;
}

输出:

  leftPointer: -1 rightPointer: 7
  leftPointer2: 0 rightPointer2: 4
  leftPointer: 0 rightPointer: 4
  leftPointer2: 1 rightPointer2: 3
  leftPointer: 1 rightPointer: 3
  leftPointer2: 3 rightPointer2: 2
  leftPointer: -2 rightPointer: 3
  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

一旦leftPointer > rightPointer它不应该进入,但确实如此。以及这些值如何设置为-23

0 个答案:

没有答案