0
$\begingroup$
public class SortAlgorithm {
public static void sorting(int[] A){
    quickLevel_sort(A, 0, A.length - 1);
}

private static void mergeLevel_Sort(int[] A, int begin, int end) {
    if (begin < end) {
        int middle = (begin + end) / 2;
        quickLevel_sort(A, begin, middle);
        quickLevel_sort(A, middle + 1, end);
        merge(A, begin, middle, end);
    }
}

private static void quickLevel_Sort(int[] A, int begin, int end) {
    if (begin < end) {
        int middle = partition(A, begin, end);
        mergeLevel_sort(A, begin, middle - 1);
        mergeLevel_sort(A, middle + 1, end);
    }
}}

I want to find the complexity of this function, but it isn't very clear because mergelevel and quicklevel are calling each other recursively. I hope someone can give me some tips

The "merge" function is used in merge sort to merge two sorted arrays, working in O(n) time complexity. The "partition" function, used in quicksort, selects the first element as the pivot and finds its correct location in the array, placing it there. Its complexity is also O(n).

$\endgroup$
2
  • $\begingroup$ That’s kind of hard to say without knowing what “merge” does. Or “partition”. $\endgroup$
    – gnasher729
    Commented Feb 21 at 8:58
  • $\begingroup$ You are right I edited the question $\endgroup$
    – Arugo
    Commented Feb 21 at 10:48

1 Answer 1

0
$\begingroup$

Let $M(n)$ be the runtime of mergeLevel on an input of size $n$, and let $Q$ be the runtime of quickLevel on an input of size $n$.

By inspecting the code, we see that $M(n) = 2Q(\frac{n}{2}) + n$ and $Q(n) \leq n + \max_{1 \leq i < n} M(n - i) + M(i)$. We can then just substitute, and henceforth ignore $M$:

$$Q(n) \leq 2n + 2\max_{1 \leq i < n} Q(\frac{n - i}{2}) + Q(\frac{i}{2})$$

The worst case for the maximum is going to be $i = 1$, which leads us to $Q(n) = O(n^2)$.

$\endgroup$
3
  • $\begingroup$ and in the best case, "i" would be N/2 because the pivot will be the median of the array. is that right? $\endgroup$
    – Arugo
    Commented Feb 21 at 13:45
  • 1
    $\begingroup$ How is the worst complexity $O(n^2)$, every two levely the input is necessarily halved in the worst čase due to the merge level. $\endgroup$ Commented Feb 22 at 11:48
  • 1
    $\begingroup$ "Q(n)=2n + 2*Q((n-1)/2) + const" means that Q(n) = O(n*log(n)) $\endgroup$
    – Bulat
    Commented Apr 26 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.