|
3 | 3 | /** Here, we are implementing InsertionSort where we sort the array in increasing (or more precisely, non-decreasing)
|
4 | 4 | * order.
|
5 | 5 | *
|
6 |
| - * Brief Description: |
7 |
| - * InsertionSort is a simple comparison-based sorting algorithm that builds the final sorted array one element at a |
8 |
| - * time. It works by repeatedly taking an element from the unsorted portion of the array and inserting it into its |
9 |
| - * correct position within the sorted portion. At the kth iteration, we take the element arr[k] and insert |
10 |
| - * it into arr[0, k-1] following sorted order, returning us arr[0, k] in sorted order. |
11 |
| - * |
12 | 6 | * Implementation Invariant:
|
13 | 7 | * The loop invariant is: at the end of kth iteration, the first (k+1) items in the array are in sorted order.
|
14 | 8 | * At the end of the (n-1)th iteration, all n items in the array will be in sorted order.
|
15 |
| - * (Note: the loop invariant here slightly differs from the lecture slides as we are using 0-based indexing.) |
16 |
| - * |
17 |
| - * Complexity Analysis: |
18 |
| - * Time: |
19 |
| - * - Worst case (reverse sorted array): O(n^2) |
20 |
| - * - Average case: O(n^2) |
21 |
| - * - Best case (sorted array): O(n) |
22 |
| - * |
23 |
| - * In the worst case, inserting an element into the sorted array of length m requires us to iterate through the |
24 |
| - * entire array, requiring O(m) time. Since InsertionSort does this insertion (n - 1) times, the time complexity |
25 |
| - * of InsertionSort in the worst case is 1 + 2 + ... + (n-2) + (n-1) = O(n^2). |
26 |
| - * |
27 |
| - * In the best case of an already sorted array, inserting an element into the sorted array of length m requires |
28 |
| - * O(1) time as we insert it directly behind the first position of the pointer in the sorted array. Since InsertionSort |
29 |
| - * does this insertion (n-1) times, the time complexity of InsertionSort in the best case is O(1) * (n-1) = O(n). |
30 | 9 | *
|
31 |
| - * Space: |
32 |
| - * - O(1) since sorting is done in-place |
| 10 | + * Note: |
| 11 | + * 1. the loop invariant here slightly differs from the lecture slides as we are using 0-based indexing |
| 12 | + * 2. Insertion into the sorted portion is done byb 'bubbling' elements as in bubble sort |
33 | 13 | */
|
34 | 14 |
|
35 | 15 | public class InsertionSort {
|
|
0 commit comments