N
N
NoMoneyException2016-09-26 00:03:27
Algorithms
NoMoneyException, 2016-09-26 00:03:27

How does quicksort work?

Hello. Something I'm sitting, I can't drill into quicksort's code. I understand the principle, but I can’t understand the little things, exceptional situations in which we don’t have 3 elements on the sides and in general everything fits perfectly, as in training articles.
For example: if we have a different number of elements on the sides of the reference, with what will we change those that did not find a pair? Another question: if we have a number to the left of the pivot element and 100 to the right, what prevents the counter from finding an element that matches the condition on the other side? I can't find a constraint in the condition that forbids him to go to the other side and select an element there. How does the code deal with an element that is equal to pivot, and can it be done differently?
Thanks :)

public static void sort(int arr[], int s, int f) {
        if (arr == null)
            throw new IllegalArgumentException();
        if (arr.length == 0 || s > f || s < 0 || f < 0)
            return;

        int i = s;
        int j = f;
        int m = s + r.nextInt(f - s + 1);
        int pivot = arr[m];

        while (i <= j) {
            while (arr[i] < pivot) {
                i++;
            }
            while (arr[j] > pivot) {
                j--;
            }

            if (i <= j) {
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i++;
                j--;
            }

            if (s < j)
                sort(arr, s, j);
            if (f > i)
                sort(arr, i, f);
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-09-26
@eugene_leshchinskiy

First.
Your code is clearly unorthodox, and in my opinion it does unnecessary sorts.
UPD. The algorithmic complexity of such a code is of the order of O(n² log n), I can’t find a more accurate boundary, and does it make sense?
Second.
Let the array be sorted in descending order, one number on the left, one hundred on the right dividing 100. Let's say 101, [100], 99…0.
Then i = 0, j = 101, and we have an array of 0, 100, 99…1, 101.
Now i = 1, j = 100; arr[i]<pivot in span, arr[j]>pivot in span, i<j, and exchange 0, 1, 99…2, 100, 101.
At the third step, 0, 1, 2 98…3 comes out, 99, 100, 101. And this despite the fact that dividing 100 and he has long fallen into place.
When we scroll to the end of the iteration, the array will be fully sorted in ascending order.
Conclusion: the dividing element will not necessarily exactly divide the array, even though a lot of things revolve around it. And if there is a strong imbalance, some of the elements will move from a larger array to a smaller one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question