Title: Selection%20Sort
1Selection Sort
6
12
6
6
12
12
17
22
8
14
8
12
8
8
12
12
6
17
22
14
- Given n numbers to sort
- Repeat the following n-1 times
- Mark the first unsorted number
- Find the smallest unsorted number
- Swap the marked and smallest numbers
2Selection Sort
12
22
22
12
22
8
12
6
17
14
8
14
14
17
17
22
22
17
6
12
22
- Given n numbers to sort
- Repeat the following n-1 times
- Mark the first unsorted number
- Find the smallest unsorted number
- Swap the marked and smallest numbers
3Selection Sort
- Given n numbers to sort
- Repeat the following n-1 times
- Mark the first unsorted number
- Find the smallest unsorted number
- Swap the marked and smallest numbers
- How efficient is selection sort?
- In general, given n numbers to sort, it performs
n2 comparisons - Why might selection sort be a good choice?
- Simple to write code
- Intuitive
4Selection Sort
- Given n numbers to sort
- Repeat the following n-1 times
- Mark the first unsorted number
- Find the smallest unsorted number
- Swap the marked and smallest numbers
Try one!
15 3 11 19 4 7
5Bubble Sort
17
14
22
14
22
17
17
8
22
14
8
14
22
8
8
22
22
6
12
12
6
12
6
6
12
17
14
8
22
17
8
14
14
12
6
6
12
22
17
14
8
8
- Given n numbers to sort
- Repeat the following n-1 times
- For each pair of adjacent numbers
- If the number on the left is greater than the
number on the right, swap them.
6Bubble Sort
8
12
8
8
12
8
14
14
22
22
17
17
12
6
6
12
8
12
12
8
14
22
17
6
6
17
14
22
- Given n numbers to sort
- Repeat the following n-1 times
- For each pair of adjacent numbers
- If the number on the left is greater than the
number on the right, swap them.
7Bubble Sort
- Given n numbers to sort
- Repeat the following n-1 times
- For each pair of adjacent numbers
- If the number on the left is greater than the
number on the right, swap them - How efficient is bubble sort?
- In general, given n numbers to sort, it performs
n2 comparisons - The same as selection sort
- Is there a simple way to improve on the basic
bubble sort? - Yes! Stop after going through without making any
swaps - This will only help some of the time
8Bubble Sort
- Given n numbers to sort
- Repeat the following n-1 times
- For each pair of adjacent numbers
- If the number on the left is greater than the
number on the right, swap them
Try one!
15 3 11 19 4 7
9Sorting Discussion Questions
Data on elementary school students is stored
sorted by the age of the student. In preparation
for track and field day, you wish to sort the
students by their heights. Which of the sorting
methods discussed today would you use?
Explain. While running a computer program to
sort student exam scores using selection sort,
the power goes out. Fortunately, the program was
designed so it saved the scores after each swap.
Just from looking at the saved scores, what
information, if any, can you learn about the exam
scores? Would anything change if bubble sort was
used instead?