- Sorting algorithms usually fall into two complexity classes:
+ $O(n^2)$
+ $O(n\log n)$
- In some special cases, we can improve this to:
+ $O(n)$
| $n$ | $n^2$ | $n\log n$ |
|--------|-----------|--------------------|
| $10$ | $100$ | $33$ |
| $10^2$ | $10^4$ | $664$ |
| $10^3$ | $10^6$ | $9965$ |
| $10^4$ | $10^8$ | $1.3\times 10^5$ |
| $10^5$ | $10^{10}$ | $1.6\times 10^6$ |
## Applications of Sorting
- Many important problems can be directly reduced to sorting or rely on sorting in some way
## Element Uniqueness
- Given a list of $n$ elements, determine whether there are any duplicates
## Finding the Mode
- Given a list of $n$ elements, return the element that appears the most frequently
## Convex Hull
- Given $n$ 2D points, what is the polygon of smallest perimeter that contains the points?
![Convex hull](../../assets/images/convex-hull.png)
## Pragmatics of Sorting
- Suppose we'd like to alphabetize a list of names
-
Even in this simple case we face some decisions:
+
Is "Klinge" the same as "klinge"?
+
Does "Eric Manley" come before "Titus Klinge"?
+
"Meredith Moore" and "Klinge, Titus"?
-
These decisions should be included in a **comparison function** and shouldn't affect the sorting algorithm
## Sorting in Python
- Python's built-in `sort` method and `sorted` function have two extra parameters:
+
`key`: for specifying a comparison function
+
`reverse`: for specifying whether you'd like the list sorted in ascending or descending order
```py
compare = lambda s1, s2: s1.lower() < s2.lower()
names.sort(key=compare, reverse=True)
```
## Sorting in Java
- Java's built-in `Arrays.sort` method supports using a `Comparator`
```java
Comparator