name: inverse layout: true class: taylor msoe --- class: center, middle .title[ # More Sorting ## Shell Sort and Merge Sort ] ??? Toggle speaker view by pressing P Pressing C clones the slideshow view, which is the view to put on the projector if you're using speaker view. Press ? to toggle keyboard commands help. --- # Insertion Sort revisited * Insertion Sort performance: -- * Best case: $O(n)$ -- * Worst case: $O(n^2)$ -- * How could we improve this? -- * Have more work when we need to do lots of swaps -- * Could we use binary search to figure out where insert the item in the sorted portion? -- * Doesn't help, since we still need to shift all elements to make room for item -- --- * Let's look at the number of swaps needed for this example:
2
3
8
5
6
1
-- * First three sorted with no swaps
2
3
8
5
6
1
-- * Swap **5** with **8** (Total swaps: 1)
2
3
5
8
6
1
-- * Swap **6** with **8** (Total swaps: 2)
2
3
5
6
8
1
-- * Swap **1** with everything (Total swaps: 7)
1
2
3
5
6
8
--- * How could we reduce swaps?
2
3
8
5
6
1
-- * First swap **1** with **8** (Total swaps: 1)
2
3
1
5
6
8
-- * Swap **1** with **3**, then **2** (Total swaps: 3)
1
2
3
5
6
8
-- * No more swaps needed (3 instead of 7 swaps)
1
2
3
5
6
8
-- * Whenever we can swap with a big gap, it has the potential to save big --- # Shell Sort * Uses the concept of a **gap** to improve performance -- * The size of the gap is not defined as part of Shell Sort -- * Dr. Shell originally proposed $\lfloor \frac{N}{2^k} \rfloor$ as the gap size --- * 8 elements, so gap is 4 (= 8/2)
S
O
R
T
I
N
G
S
--
S
_
_
_
I
_
_
_
_
O
_
_
_
N
_
_
_
_
R
_
_
_
G
_
_
_
_
T
_
_
_
S
--- * Swap **I** with **S**, **N** with **O**, **G** with **R**, and **S** with **T**
I
N
G
S
S
O
R
T
-- * Now make use a gap of 2
I
N
G
S
S
O
R
T
I
N
G
S
S
O
R
T
I
N
G
S
R
O
S
T
I
N
G
S
R
O
S
T
I
N
G
O
R
S
S
T
I
N
G
O
R
S
S
T
--- * Now make the gap 1 (traditional Insertion Sort)
I
N
G
O
R
S
S
T
-- * Swap **G** with **N**
I
G
N
O
R
S
S
T
-- * No more swaps needed
I
G
N
O
R
S
S
T
--- # Merge Sort * A _divide and conquer_ algorithm typically implemented with recursion -- * Recursively split the array into two smaller arrays -- * Base case: arrays of length one (already sorted) -- * Progressively merge pairs of arrays back together maintaining sorted order