|
| 1 | +--- |
| 2 | +tags: |
| 3 | +- datatypes |
| 4 | +--- |
| 5 | + |
| 6 | +# Actions |
| 7 | + |
| 8 | +## Motivation |
| 9 | + |
| 10 | +[Wikipedia](https://en.wikipedia.org/wiki/Sorting_algorithm) explains it very nicely: sorting is ubiquitous in Computer Sciences. |
| 11 | +It is a simple problem ("*How can I sort the following values the most efficiently?*") that has many solutions, but still offers open problems. |
| 12 | + |
| 13 | +We only consider **correct** algorithms, i.e., one where their output is such that |
| 14 | + |
| 15 | +- each element is larger than or equal to the previous one, according to the order picked, |
| 16 | +- all the elements that were in the input are present in the output (with the same cardinality, if repetition is allowed). |
| 17 | + |
| 18 | +There are many ways of "comparing" sorting algorithms. |
| 19 | +A sorting algorithm… |
| 20 | + |
| 21 | +- has a best, worst and average case time complexity (measured in general in number of comparisons required), |
| 22 | +- has a best, worst and average case space complexity (i.e., "how much additional memory is required?"), |
| 23 | +- can be "stable" (i.e., equal values are not permutted), |
| 24 | +- uses *insertion*, *exchange*, *selection*, *merging* method, |
| 25 | +- is serial or parallel, |
| 26 | + |
| 27 | +among other properties. |
| 28 | + |
| 29 | +# Insertion Sort Algorithm |
| 30 | + |
| 31 | +This algorithm is [nicely explained and illustrated on wikipedia](https://en.wikipedia.org/wiki/Insertion_sort), and can be implemented as follows: |
| 32 | + |
| 33 | +``` |
| 34 | +!include`snippetStart="// Insertion Algorithm", snippetEnd="// Done with insertion Algorithm"` code/projects/Sorting/Sorting/Sorting.cs |
| 35 | +``` |
| 36 | + |
| 37 | +# Heapsort Algorithm |
| 38 | + |
| 39 | +We first define some helper methods: |
| 40 | + |
| 41 | +``` |
| 42 | +!include`snippetStart="// Helper methods for Heapsort", snippetEnd="// Done with helper methods for Heapsort"` code/projects/Sorting/Sorting/Sorting.cs |
| 43 | +``` |
| 44 | + |
| 45 | +and then leverage the heap structure to sort: |
| 46 | + |
| 47 | +``` |
| 48 | +!include`snippetStart="// Heapsort Algorithm", snippetEnd="// Done with heapsort Algorithm"` code/projects/Sorting/Sorting/Sorting.cs |
| 49 | +``` |
| 50 | + |
| 51 | +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. |
0 commit comments