2. How do you sort?
Assuming we want to sort an array of integers in ascending order
3. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
4. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
5 1 7 4 2
5. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
5 1 7 4 2
5 1 4 7 2
6. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
5 1 7 4 2
5 1 4 7 2
5 1 4 2 7
7. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
5 1 7 4 2
Question: How many passes do we need?
5 1 4 7 2
5 1 4 2 7
8. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
5 1 7 4 2
Question: How many passes do we need?
5 1 4 7 2
5 1 4 2 7
9. Bubble Sort – Concept
Let’s scan from left to right and swap conflicting neighboring integers!
5 7 1 4 2
5 1 7 4 2
Question: How many passes do we need?
5 1 4 7 2
5 1 4 2 7
(N – 1)
11. Selection Sort – Concept
Let’s find the smallest integer, then the 2nd-smallest, 3rd-smallest and so on!
smallest 2nd-smallest 3rd-smallest 4th-smallest 5th-smallest
This is selection sort!
13. Insertion Sort – Concept
Suppose we have a sorted array of integers already, and we want to insert
a new integer
1 3 7 2 4
sorted insert this
14. Insertion Sort – Concept
Suppose we have a sorted array of integers already, and we want to insert
a new integer
1 3 7 2 4
sorted insert this
Find the position, then shift integers right for space
1 2 3 7 4
shifted rightinserted
15. Insertion Sort – Concept
Suppose we have a sorted array of integers already, and we want to insert
a new integer
1 3 7 2 4
sorted insert this
Find the position, then shift integers right for space
1 2 3 7 4
shifted rightinserted
We do this for all integers
21. Quick Sort – Concept
Divide and Conquer – again
Choose a “pivot” and divide the array into 2 halves where the left half is
less than (or equal to) the pivot and the right half is greater than the pivot.
Conquering is simply returning the array.
5 7 3 6 2 8 4
22. Quick Sort – Concept
Divide and Conquer – again
Choose a “pivot” and divide the array into 2 halves where the left half is
less than (or equal to) the pivot and the right half is greater than the pivot.
Conquering is simply returning the array.
5 7 3 6 2 8 4
3 2 4 5 7 6 8
23. Quick Sort – Concept
Divide and Conquer – again
Choose a “pivot” and divide the array into 2 halves where the left half is
less than (or equal to) the pivot and the right half is greater than the pivot.
Conquering is simply returning the array.
5 7 3 6 2 8 4
3 2 4 5 7 6 8
3 2 4 7 6 8