Você está na página 1de 3

Self quiz on sorting:

Draw out how youd sort this list by hand with a selection sort
3 4 12 9 1 2
Selection
Value
3
4
12
9
index
0
1
2
3
---find min from arr [0 5] : 1, at arr[4], swap to head:
Value
1
4
12
9
index
0
1
2
3
---find min from arr[1 5]: 2, at arr[5], swap to 4, arr[1]
Value
1
2
12
9
index
0
1
2
3
---find min from arr[2 5]: 3, at arr[4], swap to 12, arr[2]
Value
1
2
3
9
index
0
1
2
3
---find min from arr[3-5]: 4, at arr[5], swap to 9, arr[3]
Value
1
2
3
4
index
0
1
2
3
----find min from arr[4-5]: 9 at arr[5], swap to 12, arr[4]
Value
1
2
3
4
index
0
1
2
3
Now its all sorted:
Value
1
index
0

2
1

3
2

4
3

1
4

2
5

3
4

2
5

3
4

4
5

12
4

4
5

12
4

9
5

9
4

12
5

9
4

12
5

Insertion
3 | 4 | 12 | 9 | 1 | 2 |

4 < 3 , do nothing

3 | 4 | 12 | 9 | 1 | 2 |

4 < 3

3 | 4 | 12 | 9 | 1 | 2 |

4 < 12

3 | 4 | 9 | 12 | 1 | 2 |

9 < 12, insert before 9

1 | 3 | 4 | 9 | 12 | 2 |

12 > 9

1 | 2 | 3 | 4 | 9 | 12 |

2 < 12, insert before 3

Merge sort
3 | 4 | 12 | 9 | 1 | 2 |
3 | 4 | 12 |
3 |
4 | 12 |
4 |
12 |
4 | 12 |
3 | 4 | 12 |
9 | 1 | 2 |
9 |
1 | 2 |
1 |
2 |
1 | 2 |
1 | 2 | 9 |

1 | 2 | 3 | 4 | 9 | 12 |

Quick sort [pivot always middle element]


3 | 4 | 12 | 9 | 1 | 2 |
0
1
2
3
4
5
Pivot: 12 Piv index: 2
After partition:
3 | 4 | 2 | 9 | 1 |
Pivot: 2 Piv index: 2

12 |

After partition:
1 | 2 |
4 | 9 | 3 |
After partition:
1 | 2 |
Pivot: 1 Piv index: 0
After partition:
1 |
2 |

12 |

4 | 9 | 3 |
Pivot: 9 Piv index: 3

4 | 3 |

9 |

12 |

12 |

Pivot: 4 Piv index: 2


1 |

2 |

4 |

3 |

9 |

12 |

Now we can combine all our arrays together in sorted order:


1 | 2 | 3 | 4 | 9 | 12 |

Whats a terrible pivot to quick sort this list?


6, 5 , 4, 3, 2, 1
6 | 5 | 4 | 3 | 2 | 1 |
Pivot: 6 Piv index: 0
1 | 5 | 4 | 3 | 2 |

6 |

1 |
Pivot: 1 Piv index: 0

5 | 4 | 3 | 2 |

1 |
Pivot: 5 Piv index: 1

2 | 4 | 3 |

1 |
Pivot: 2 Piv index: 1

2 |

1 |
2 |
Pivot: 4 Piv index: 2
1 | 2 | 3 | 4 | 5 | 6 |

5 |

4 | 3 |

4 |

3 |

6 |

6 |

5 |

5 |

6 |

6 |

Você também pode gostar