- **Key idea**:
+ Repeatedly find smallest element
-
**Pseudocode**:
+
For $i = 0$ to $n-1$
+
Find smallest of elements $i\ldots n-1$
+
Move that element to the $i$th position
-
What is the time-complexity?
+
Depends!
![selection sort animation](https://upload.wikimedia.org/wikipedia/commons/9/94/Selection-Sort-Animation.gif)
## Selection Sort
- **Given an array of $n$ elements**:
+ For $i = 0$ to $n-1$:
* Find smallest of elements $i\ldots n-1$
* Move that element to the $i$th position
---
-
Normally this algorithm would take $O(n^2)$ since finding the smallest element takes $O(n)$ time
-
But this can be sped up using a different data structure
# Heaps
## Heaps
- A **heap** is a data structure that efficiently supports the following operations:
1. `extract_min`: removes the minimum element
2. `insert`: adds a new element
-
In brief, a heap is a **binary tree** that satisfies the following property:
+ For every node `n`, the value of `n` is less than the value of all its descendants
## Heaps