diff options
| author | mo khan <mo@mokhan.ca> | 2021-09-19 16:20:13 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2021-09-19 16:20:13 -0600 |
| commit | cbc47d4e56a04cc4295a0dc5f09b52a356a455f1 (patch) | |
| tree | 4b4cefd6a8d5e86ba9142376d4f869a954059339 | |
| parent | bdba2ba970db144618e756505274955c500a292c (diff) | |
complete 2-2.2
| -rw-r--r-- | exercises/2.2-2/selection_sort_test.go | 6 | ||||
| -rw-r--r-- | notes.md | 20 |
2 files changed, 24 insertions, 2 deletions
diff --git a/exercises/2.2-2/selection_sort_test.go b/exercises/2.2-2/selection_sort_test.go index e4abc5d..2b175e9 100644 --- a/exercises/2.2-2/selection_sort_test.go +++ b/exercises/2.2-2/selection_sort_test.go @@ -7,11 +7,13 @@ func Sort(i *[]int) { n := len(A) for i := 0; i < n; i++ { + min := i for j := i + 1; j < n; j++ { - if A[j] < A[i] { - A[i], A[j] = A[j], A[i] + if A[j] < A[min] { + min = j } } + A[i], A[min] = A[min], A[i] } } @@ -460,6 +460,26 @@ the rate of growth in determining computational efficiency for large inputs. > manner for the first `n - 1` elements of `A`. Write pseudocode for *selection sort*. + + n = A.length + for i = 1 to n - 1 { + min = i + for j = i + 1 to n { + if A[j] < A[min] + min = j + A[i], A[min] = A[min], A[i] + + What loop invariant does this algorithm maintain? + + * intialization: inner loop initializes to the right index of the outer loop + * maintenance: with the inner right array of the outer array. + * termination: when end of loop is reached + Why does it need to run for only the first n-1 elements, rather than for all `n` elements? + + * The last element of the array should has nothing to be compared against. + Give the best-case and worst-case running times of selection sort in 𝚯-notation. + + = 𝚯(n^2). two loops, one nested within the other. |
