Intermediate Python Learning about Sorts!
Intermediate Python Learning about Sorts!
import random
nums = [random.randrange(0, 100) for i in range(10)]
2 4 3 1 5 9 100 0
Selection Sort
Repeat n-1 times: (n is the length of the list)
1. Find the minimum of the remaining list
2. Swap it with the number you are changing
For example:
23 1 4 5 7 3 2
We’re starting with position 0: the 23. We’re
searching everything from position 0 onwards.
23 1 4 5 7 3 2
Found the minimum
1 23 4 5 7 3 2
…and swap
Continuing Selection Sort
1 23 4 5 7 3 2
Now we’re swapping position 1: the 23, and we’re
looking for the minimum of position 1 onwards.
1 23 4 5 7 3 2
1 2 4 5 7 3 23
Important note: What if the minimum is the number you’re
trying to swap? Then swap it with itself.
Insertion Sort
Repeat n-1 times: (n is the length of the list)
1. Take the number you’re moving
2. If it’s smaller than the number left of it, move it left.
a. Repeat until it’s not or until it’s at the front.
For example: 23 1 4 5 7 3 2
We’re starting with position 1: the 1. Is it less
than the 23?
23 1 4 5 7 3 2
Move it
1 23 4 5 7 3 2
Continuing Insertion Sort
1 23 4 5 7 3 2
Now we check the 4. Is it less than 23?
1 23 4 5 7 3 2
Move it
Is it less than 1? No
1 4 23 5 7 3 2
Important note: Don’t start with the first number. Start
with the second
Thank you for coming!
Contact us at
[email protected]
If you want to continue your coding education or want
help with other subjects like math and science, contact us!
Ertan: [email protected]
Harrison: [email protected]