D
D
Dmitry2018-03-20 19:51:57
Java
Dmitry, 2018-03-20 19:51:57

Find bugs in the implementation of quicksort?

This code fails with a StackOverflowError.
Point out the places where I should look for the error.
Java complains about second recursive call in quickSort method

spoiler
class Sort {
    public static void sort(Integer[] array) {
        quickSort(array, 0, array.length);
    }

    private static void quickSort(Integer[] array, int begin, int end) {
        if (begin < end) {
            int p = partition(array, begin, end);
            quickSort(array, begin, p);
            quickSort(array, p, end);
        }
    }

    private static int partition(Integer[] array, int begin, int end) {
        int pivot = array[begin];
        int i = begin;
        int j = end - 1;

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

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

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

            // swap(array[i], array[j]);
            int t = array[i];
            array[i] = array[j];
            array[j] = t;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-03-20
@cosmoskey

Run this code in your mind for a unit length interval.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question