34
Chapter 2
I
Selection sort
Let’s put on our computer science hats and see how long this will take to
run. Remember that O(
n
) time means you touch
every element in a list
once. For example, running simple search over the list of artists means
looking at each artist once.
To find the artist
with the highest play count, you have to check each
item in the list. This takes O(
n
) time, as you just saw. So you have an
operation that takes O(
n
) time, and you have to do that
n
times:
This takes O(
n
×
n
) time or O(
n
2
) time.
Sorting algorithms are very useful.
Now you can sort
• Names in a phone book
• Travel dates
• Emails (newest to oldest)
35
Selection
sort is a neat algorithm, but it’s not very fast. Quicksort is a
faster sorting algorithm that only takes O(
n
log
n
) time. It’s coming up
in the next chapter!
Dostları ilə paylaş: