'Correctness of the Partition Scheme

The code I was trying to use:

private static int partition(int[] arr, int lower, int upper) {
        int pivot, i, j, temp;
        pivot = arr[(int) (upper + lower) / 2];
        i = lower - 1;
        j = upper + 1;

        while (true) {
            do {
                i++;
            } while (arr[i] < pivot);

            do {
                j--;
            } while (arr[j] > pivot);

            if (i >= j) {
                return j;
            }

            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

And it did not work. I tested it using the array {6,1,3,4,5}, lower = 0, upper = 4.

  1. The pivotIndex is 2, which corresponds to 3.
  2. Start moving i, stop at 6 since it is greater than the pivot. Now i = 0.
  3. Start moving j, stop at 3 since it equals the pivot. Now j = 2.
  4. Swap i and j (6&3). now the array is {3,1,6,4,5}.
  5. Start moving i, stop at 6 since it is greater than the pivot. Now i = 2.
  6. Start moving j, stop at 1 since it is less than pivot. Now j = 1.
  7. Since i>j, return j = 1.

And as for result, I got this weird {3,1,6,4,5} with pivot index = 1.

Is there something wrong with my calculation? Or is it the algorithm's fault?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source