You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
!include`snippetStart="// Helper method", snippetEnd="// Done with helper method."` code/projects/Sorting/Sorting/Sorting.cs
49
+
!include`snippetStart="// Helper methods", snippetEnd="// Done with helpers method."` code/projects/Sorting/Sorting/Sorting.cs
50
50
```
51
51
52
52
## Insertion Sort Algorithm
@@ -57,6 +57,9 @@ This algorithm is [nicely explained and illustrated on wikipedia](https://en.wik
57
57
!include`snippetStart="// Insertion Algorithm", snippetEnd="// Done with insertion Algorithm"` code/projects/Sorting/Sorting/Sorting.cs
58
58
```
59
59
60
+
[As explained on wikipedia](https://en.wikipedia.org/wiki/Insertion_sort#Best,_worst,_and_average_cases), the simplest worst case input is an array sorted in reverse order.
61
+
With an array sorted in reverse order, every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element. This gives insertion sort a quadratic running time (i.e., $O(n^2)$).
62
+
60
63
## Heapsort Algorithm
61
64
62
65
We first define some helper methods:
@@ -73,6 +76,9 @@ and then leverage the heap structure to sort:
73
76
74
77
Note that `PercDown` builds a *max heap*: once the values are "pre-sorted **greater value first**", removing the first one to move it to the *end* of the list makes the list sorted from smallest to greatest value once we are done.
75
78
79
+
The `PercDown` is first called $N / 2$ times, which is equivalent to $O(n)$.
80
+
Its complexity is $O(\log(n))$, and it is called a second time $O(n)$ times.
81
+
So, we get an overall performance of $O((n + n) \times \log n) = O(n \times \log(n))$.
0 commit comments