|
3 | 3 | /** |
4 | 4 | * Here, we are implementing MergeSort where we sort the array in increasing (or more precisely, non-decreasing) |
5 | 5 | * order iteratively. |
6 | | - * <p> |
7 | | - * Brief Description: |
8 | | - * The iterative implementation of MergeSort takes a bottom-up approach, where the sorting process starts by merging |
9 | | - * intervals of size 1. Intervals of size 1 are trivially in sorted order. The algorithm then proceeds to merge |
10 | | - * adjacent sorted intervals, doubling the interval size with each merge step, until the entire array is fully sorted. |
11 | | - * <p> |
12 | | - * Implementation Invariant: |
13 | | - * At each iteration of the merging process, the main array is divided into sub-arrays of a certain interval |
14 | | - * size (interval). Each of these sub-arrays is sorted within itself. The last sub-array may not be of size |
15 | | - * interval, but it is still sorted since its size is necessarily less than interval. |
16 | | - * <p> |
17 | | - * Complexity Analysis: |
18 | | - * Time: |
19 | | - * - Worst case: O(nlogn) |
20 | | - * - Average case: O(nlogn) |
21 | | - * - Best case: O(nlogn) |
22 | | - * <p> |
23 | | - * Given two sorted arrays of size p and q, we need O(p + q) time to merge the two arrays into one sorted array, since |
24 | | - * we have to iterate through every element in both arrays once. |
25 | | - * <p> |
26 | | - * At the 1st level of the merge process, our merging subroutine involves n sub-arrays of size 1, taking O(n) time. |
27 | | - * At the 2nd level of the merge process, our merging subroutine involves (n/2) sub-arrays of size 2, taking O(n) time. |
28 | | - * At the kth level of the merge process, our merging subroutine involves (n/(2^(k-1))) sub-arrays of size (2^(k-1)), |
29 | | - * taking O(n) time. |
30 | | - * <p> |
31 | | - * Since interval doubles at every iteration of the merge process, there are logn such levels. Every level takes |
32 | | - * O(n) time, hence overall time complexity is n * logn = O(nlogn) |
33 | | - * <p> |
34 | | - * Regardless of how sorted the input array is, MergeSort carries out the partitioning and merging process, so the |
35 | | - * time complexity of MergeSort is O(nlogn) for all cases. |
36 | | - * <p> |
37 | | - * Space: |
38 | | - * - O(n) since we require a temporary array to temporarily store the merged elements in sorted order |
39 | 6 | */ |
40 | 7 |
|
41 | 8 | public class MergeSort { |
|
0 commit comments