Grokking Algorithms


from time import sleep def



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

from time import sleep
def print_items2(list):
for item in list:
sleep(1)
print item
Before it prints out an item, it will pause for 1 second. Suppose you 
print a list of five items using both functions.
Both functions loop through the list once, so they’re both O(
n
) time. 
Which one do you think will be faster in practice? I think 
print_items 
will be much faster because it doesn’t pause for 1 second before printing 
an item. So even though both functions are the same speed in Big O 
notation,
print_items
is faster in practice. When you write Big O 
notation like O(
n
), it really means this.
c
is some fixed amount of time that your algorithm takes. It’s called the 
constant
. For example, it might be
10 milliseconds *
n
for 
print_
items
versus 
1 second

n
for 
print_items2



68
Chapter 4
 
 
I
 
 
Quicksort
You usually ignore that constant, because if two algorithms have 
different Big O times, the constant doesn’t matter. Take binary search 
and simple search, for example. Suppose both algorithms had these 
constants.
You might say, “Wow! Simple search has a constant of 10 milliseconds
but binary search has a constant of 1 second. Simple search is way 
faster!” Now suppose you’re searching a list of 4 billion elements. Here 
are the times.
As you can see, binary search is still way faster. That constant didn’t 
make a difference at all.
But sometimes the constant 
can
make a difference. Quicksort versus 
merge sort is one example. Quicksort has a smaller constant than 
merge sort. So if they’re both O(
n
log
 n
) time, quicksort is faster. And 
quicksort is faster in practice because it hits the average case way more 
often than the worst case.
So now you’re wondering: what’s the average case versus the worst case?

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   35   36   37   38   39   40   41   42   ...   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