Grokking Algorithms



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

Chapter 4
 
 
I
 
 
Quicksort
For example, suppose you pick 3 as the pivot. You call quicksort on the 
sub-arrays. 
The sub-arrays get sorted, and then you combine the whole thing to get 
a sorted array. This works even if you choose 5 as the pivot.
This works with any element as the pivot. So you can sort an array 
of five elements. Using the same logic, you can sort an array of six 
elements, and so on.


65
Quicksort
Here’s the code for quicksort:
def quicksort(array):
if len(array) < 2:
return array
Base case: arrays with 0 or 1 element are already “sorted.”
else:
pivot = array[0]
Recursive case
less = [i for i in array[1:] if i <= pivot]
Sub-array of all the elements
less than the pivot
greater = [i for i in array[1:] if i > pivot]
Sub-array of all the elements
greater than the pivot
return quicksort(less) + [pivot] + quicksort(greater)
print quicksort([10, 5, 2, 3])
Inductive proofs
You just got a sneak peak into
 inductive proofs!
Inductive proofs are one 
way to prove that your algorithm works. Each inductive proof has two 
steps: the base case and the inductive case. Sound familiar? For example, 
suppose I want to prove that I can climb to the top of a ladder. In the 
inductive case, if my legs are on a rung, I can put my legs on the next rung. 
So if I’m on rung 2, I can climb to rung 3. That’s the inductive case. For 
the base case, I’ll say that my legs are on rung 1. Therefore, I can climb the 
entire ladder, going up one rung at a time.
You use similar reasoning for quicksort. In the base case, I showed that the 
algorithm works for the base case: arrays of size 0 and 1. In the inductive 
case, I showed that if quicksort works for an array of size 1, it will work 
for an array of size 2. And if it works for arrays of size 2, it will work for 
arrays of size 3, and so on. Then I can say that quicksort will work for all 
arrays of any size. I won’t go deeper into inductive proofs here, but they’re 
fun and go hand-in-hand with D&C.


66

Yüklə 348,95 Kb.

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