Grokking Algorithms



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə38/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   34   35   36   37   38   39   40   41   ...   122
grokking-algorithms-illustrated-programmers-curious

Chapter 4
 
 
I
 
 
Quicksort
Big O notation revisited
Quicksort is unique because its speed depends on the pivot you choose. 
Before I talk about quicksort, let’s look at the most common Big O run 
times again.
The example times in this chart are estimates if you perform 10 
operations per second. These graphs aren’t precise—they’re just there 
to give you a sense of how different these run times are. In reality, your 
computer can do way more than 10 operations per second.
Each run time also has an example algorithm attached. Check out 
selection sort, which you learned in chapter 2. It’s O(
n
2
). That’s a pretty 
slow algorithm.
There’s another sorting algorithm called 
merge sort
, which is
O(
n
log 
n
). Much faster! Quicksort is a tricky case. In the worst case, 
quicksort takes O(
n
2
) time.
It’s as slow as selection sort! But that’s the worst case. In the average 
case, quicksort takes O(
n
log 
n
) time. So you might be wondering:
• What do 
worst case
and 
average case
mean here?
• If quicksort is O(
n
log 
n
) on average, but merge sort is O(
n
log 
n

always, why not use merge sort? Isn’t it faster?
Estimates based on a slow computer that performs 10 operations per second


67
Big O notation revisited
Merge sort vs. quicksort
Suppose you have this simple function to print every item in a list:
def print_items(list):
for item in list:
print item
This function goes through every item in the list and prints it out. 
Because it loops over the whole list once, this function runs in O(
n

time. Now, suppose you change this function so it sleeps for 1 second 
before it prints out an item:

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   34   35   36   37   38   39   40   41   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin