SlideShare a Scribd company logo
1 of 14
1
Randomizing Quicksort
• Randomly permute the elements of the input
array before sorting
• OR ... modify the PARTITION procedure
– At each step of the algorithm we exchange element
A[p] with an element chosen at random from A[p…r]
– The pivot element x = A[p] is equally likely to be any
one of the r – p + 1 elements of the subarray
2
Randomized Algorithms
• No input can elicit worst case behavior
– Worst case occurs only if we get “unlucky” numbers
from the random number generator
• Worst case becomes less likely
– Randomization can NOT eliminate the worst-case but
it can make it less likely!
3
Randomized PARTITION
Alg.: RANDOMIZED-PARTITION(A, p, r)
i ← RANDOM(p, r)
exchange A[p] A[i]↔
return PARTITION(A, p, r)
4
Randomized Quicksort
Alg. : RANDOMIZED-QUICKSORT(A, p, r)
if p < r
then q ← RANDOMIZED-PARTITION(A, p, r)
RANDOMIZED-QUICKSORT(A, p, q)
RANDOMIZED-QUICKSORT(A, q + 1, r)
5
Notation
• Rename the elements of A as z1, z2, . . . , zn, with
zi being the i-th smallest element
• Define the set Zij = {zi , zi+1, . . . , zj } the set of
elements between zi and zj, inclusive
106145389 72
z1z2 z9 z8 z5z3 z4 z6 z10 z7
6
Total Number of Comparisons
in PARTITION
i+1 n
=X
i n-1
∑
−
=
1
1
n
i
∑+=
n
ij 1 ijX
• Total number of comparisons X performed by
the algorithm:
• Define Xij = I {zi is compared to zj }
7
Expected Number of Total
Comparisons in PARTITION
• Compute the expected value of X:
=][XE
by linearity
of expectation
the expectation of Xij is equal
to the probability of the event
“zi is compared to zj”
=





∑ ∑
−
= +=
1
1 1
n
i
n
ij
ijXE [ ]=∑ ∑
−
= +=
1
1 1
n
i
n
ij
ijXE
∑ ∑
−
= +=
=
1
1 1
}Pr{
n
i
n
ij
ji ztocomparedisz
indicator
random variable
8
Comparisons in PARTITION :
Observation 1
• Each pair of elements is compared at most once
during the entire execution of the algorithm
– Elements are compared only to the pivot point!
– Pivot point is excluded from future calls to PARTITION
9
Comparisons in PARTITION:
Observation 2
• Only the pivot is compared with elements in both
partitions!
z1z2 z9 z8 z5z3 z4 z6 z10 z7
106145389 72
Z1,6= {1, 2, 3, 4, 5, 6} Z8,9 = {8, 9, 10}{7}
pivot
Elements between different partitions
are never compared!
10
Comparisons in PARTITION
• Case 1: pivot chosen such as: zi < x < zj
– zi and zj will never be compared
• Case 2: zi or zj is the pivot
– zi and zj will be compared
– only if one of them is chosen as pivot before any
other element in range zi to zj
106145389 72
z1z2 z9 z8 z5z3 z4 z6 z10 z7
Z1,6= {1, 2, 3, 4, 5, 6} Z8,9 = {8, 9, 10}{7}
Pr{ }?i jz is compared to z
11
Probability of comparing zi with zj
= 1/( j - i + 1) + 1/( j - i + 1) = 2/( j - i + 1)
zi is compared to zj
zi is the first pivot chosen from Zij
=Pr{ }
Pr{ }
zj is the first pivot chosen from Zij
Pr{ }
OR+
•There are j – i + 1 elements between zi and zj
– Pivot is chosen randomly and independently
– The probability that any particular element is the first
one chosen is 1/( j - i + 1)
12
Number of Comparisons in PARTITION
1 1 1 1
1 1 1 1 1 1 1
2 2 2
[ ] (lg )
1 1
n n n n i n n n
i j i i k i k i
E X O n
j i k k
− − − − −
= = + = = = = =
= = < =
− + +
∑ ∑ ∑∑ ∑∑ ∑
)lg( nnO=
⇒ Expected running time of Quicksort using
RANDOMIZED-PARTITION is O(nlgn)
∑ ∑
−
= +=
=
1
1 1
}Pr{][
n
i
n
ij
ji ztocomparediszXE
Expected number of comparisons in PARTITION:
(set k=j-i) (harmonic series)
13
Alternative Average-Case
Analysis of Quicksort
• See Problem 7-2, page 16
• Focus on the expected running time of
each individual recursive call to Quicksort,
rather than on the number of comparisons
performed.
• Use Hoare partition in our analysis.
14
Worst-Case Analysis
T(n) = max (T(q) + T(n - q - 1)) + Θ(n)
0 ≤ q ≤ n-1
1.the time to sort the left partition with q elements, plus
2.the time to sort the right partition with N-q-1 elements, plus
3.the time to build the partitions
where q ranges from 0 to n-1 since the procedure PARTITION
produces two sub-problems with total size n-1
---------- Substitution method: Guess T(n) ≤ cn2
T(n) ≤ max (cq2
+ c(n - q - 1)2
) + Θ(n)
0 ≤ q ≤ n-1
= c · max (q2
+ (n - q - 1)2
) + Θ(n)
0 ≤ q ≤ n-1
Take derivatives to get maximum at q = 0, n-1:
T(n) ≤ c(n - 1)2
+ Θ(n) ≤ cn2
- 2c(n - 1) + 1 + Θ(n) ≤ cn2
Therefore, the worst case running time is Θ(n2
)

More Related Content

What's hot

Optimization for Deep Learning
Optimization for Deep LearningOptimization for Deep Learning
Optimization for Deep LearningSebastian Ruder
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2chidabdu
 
Markov decision process
Markov decision processMarkov decision process
Markov decision processHamed Abdi
 
AI - Introduction to Bellman Equations
AI - Introduction to Bellman EquationsAI - Introduction to Bellman Equations
AI - Introduction to Bellman EquationsAndrew Ferlitsch
 
Rabin Carp String Matching algorithm
Rabin Carp String Matching  algorithmRabin Carp String Matching  algorithm
Rabin Carp String Matching algorithmsabiya sabiya
 
Basic Traversal and Search Techniques
Basic Traversal and Search TechniquesBasic Traversal and Search Techniques
Basic Traversal and Search TechniquesSVijaylakshmi
 
AI Uninformed Search Strategies by Examples
AI Uninformed Search Strategies by ExamplesAI Uninformed Search Strategies by Examples
AI Uninformed Search Strategies by ExamplesAhmed Gad
 
Time and space complexity
Time and space complexityTime and space complexity
Time and space complexityAnkit Katiyar
 
Evaluation of Expression in Query Processing
Evaluation of Expression in Query ProcessingEvaluation of Expression in Query Processing
Evaluation of Expression in Query ProcessingNeel Shah
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSGayathri Gaayu
 

What's hot (20)

Optimization for Deep Learning
Optimization for Deep LearningOptimization for Deep Learning
Optimization for Deep Learning
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
 
Markov decision process
Markov decision processMarkov decision process
Markov decision process
 
KMP String Matching Algorithm
KMP String Matching AlgorithmKMP String Matching Algorithm
KMP String Matching Algorithm
 
AI - Introduction to Bellman Equations
AI - Introduction to Bellman EquationsAI - Introduction to Bellman Equations
AI - Introduction to Bellman Equations
 
Rabin Carp String Matching algorithm
Rabin Carp String Matching  algorithmRabin Carp String Matching  algorithm
Rabin Carp String Matching algorithm
 
Basic Traversal and Search Techniques
Basic Traversal and Search TechniquesBasic Traversal and Search Techniques
Basic Traversal and Search Techniques
 
AI Uninformed Search Strategies by Examples
AI Uninformed Search Strategies by ExamplesAI Uninformed Search Strategies by Examples
AI Uninformed Search Strategies by Examples
 
Time and space complexity
Time and space complexityTime and space complexity
Time and space complexity
 
Daa unit 4
Daa unit 4Daa unit 4
Daa unit 4
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Evaluation of Expression in Query Processing
Evaluation of Expression in Query ProcessingEvaluation of Expression in Query Processing
Evaluation of Expression in Query Processing
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMS
 
08 Hash Tables
08 Hash Tables08 Hash Tables
08 Hash Tables
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Hash table
Hash tableHash table
Hash table
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
Shortest Path in Graph
Shortest Path in GraphShortest Path in Graph
Shortest Path in Graph
 

Viewers also liked

Srs hospital management
Srs hospital managementSrs hospital management
Srs hospital managementmaamir farooq
 
Hostpital management system(srs)
Hostpital management system(srs)Hostpital management system(srs)
Hostpital management system(srs)maamir farooq
 
project plan document(ppd)
project plan document(ppd)project plan document(ppd)
project plan document(ppd)maamir farooq
 
Proposal template db jooob
Proposal template db jooobProposal template db jooob
Proposal template db jooobmaamir farooq
 
Greedy algo revision 2
Greedy algo revision 2Greedy algo revision 2
Greedy algo revision 2maamir farooq
 

Viewers also liked (9)

Hu312 pm assignment
Hu312 pm assignmentHu312 pm assignment
Hu312 pm assignment
 
Osla b manual
Osla b manualOsla b manual
Osla b manual
 
Report mangla
Report manglaReport mangla
Report mangla
 
Srs hospital management
Srs hospital managementSrs hospital management
Srs hospital management
 
Hostpital management system(srs)
Hostpital management system(srs)Hostpital management system(srs)
Hostpital management system(srs)
 
project plan document(ppd)
project plan document(ppd)project plan document(ppd)
project plan document(ppd)
 
Proposal template db jooob
Proposal template db jooobProposal template db jooob
Proposal template db jooob
 
Quicksort
QuicksortQuicksort
Quicksort
 
Greedy algo revision 2
Greedy algo revision 2Greedy algo revision 2
Greedy algo revision 2
 

Similar to Randomizing quicksort algorith with example

Similar to Randomizing quicksort algorith with example (20)

Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And Analysis
 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptx
 
Lec10
Lec10Lec10
Lec10
 
Randomized Algorithm- Advanced Algorithm
Randomized Algorithm- Advanced AlgorithmRandomized Algorithm- Advanced Algorithm
Randomized Algorithm- Advanced Algorithm
 
quick and merge.pptx
quick and merge.pptxquick and merge.pptx
quick and merge.pptx
 
Sorting
SortingSorting
Sorting
 
Algorithms - "quicksort"
Algorithms - "quicksort"Algorithms - "quicksort"
Algorithms - "quicksort"
 
Top school in noida
Top school in noidaTop school in noida
Top school in noida
 
Lec10
Lec10Lec10
Lec10
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
 
Analisys of Selection Sort and Bubble Sort
Analisys of Selection Sort and Bubble SortAnalisys of Selection Sort and Bubble Sort
Analisys of Selection Sort and Bubble Sort
 
Sorting
SortingSorting
Sorting
 
Sorting
SortingSorting
Sorting
 
07 Analysis of Algorithms: Order Statistics
07 Analysis of Algorithms: Order Statistics07 Analysis of Algorithms: Order Statistics
07 Analysis of Algorithms: Order Statistics
 
Quick sort
Quick sortQuick sort
Quick sort
 

More from maamir farooq (20)

Ooad lab1
Ooad lab1Ooad lab1
Ooad lab1
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 02
Lesson 02Lesson 02
Lesson 02
 
Php client libray
Php client librayPhp client libray
Php client libray
 
Swiftmailer
SwiftmailerSwiftmailer
Swiftmailer
 
Lect15
Lect15Lect15
Lect15
 
Lec 7
Lec 7Lec 7
Lec 7
 
Lec 6
Lec 6Lec 6
Lec 6
 
Lec 5
Lec 5Lec 5
Lec 5
 
J query 1.7 cheat sheet
J query 1.7 cheat sheetJ query 1.7 cheat sheet
J query 1.7 cheat sheet
 
Assignment
AssignmentAssignment
Assignment
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Lec 3
Lec 3Lec 3
Lec 3
 
Lec 2
Lec 2Lec 2
Lec 2
 
Lec 1
Lec 1Lec 1
Lec 1
 
Css summary
Css summaryCss summary
Css summary
 
Manual of image processing lab
Manual of image processing labManual of image processing lab
Manual of image processing lab
 
Session management
Session managementSession management
Session management
 
Data management
Data managementData management
Data management
 
Content provider
Content providerContent provider
Content provider
 

Recently uploaded

Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

Randomizing quicksort algorith with example

  • 1. 1 Randomizing Quicksort • Randomly permute the elements of the input array before sorting • OR ... modify the PARTITION procedure – At each step of the algorithm we exchange element A[p] with an element chosen at random from A[p…r] – The pivot element x = A[p] is equally likely to be any one of the r – p + 1 elements of the subarray
  • 2. 2 Randomized Algorithms • No input can elicit worst case behavior – Worst case occurs only if we get “unlucky” numbers from the random number generator • Worst case becomes less likely – Randomization can NOT eliminate the worst-case but it can make it less likely!
  • 3. 3 Randomized PARTITION Alg.: RANDOMIZED-PARTITION(A, p, r) i ← RANDOM(p, r) exchange A[p] A[i]↔ return PARTITION(A, p, r)
  • 4. 4 Randomized Quicksort Alg. : RANDOMIZED-QUICKSORT(A, p, r) if p < r then q ← RANDOMIZED-PARTITION(A, p, r) RANDOMIZED-QUICKSORT(A, p, q) RANDOMIZED-QUICKSORT(A, q + 1, r)
  • 5. 5 Notation • Rename the elements of A as z1, z2, . . . , zn, with zi being the i-th smallest element • Define the set Zij = {zi , zi+1, . . . , zj } the set of elements between zi and zj, inclusive 106145389 72 z1z2 z9 z8 z5z3 z4 z6 z10 z7
  • 6. 6 Total Number of Comparisons in PARTITION i+1 n =X i n-1 ∑ − = 1 1 n i ∑+= n ij 1 ijX • Total number of comparisons X performed by the algorithm: • Define Xij = I {zi is compared to zj }
  • 7. 7 Expected Number of Total Comparisons in PARTITION • Compute the expected value of X: =][XE by linearity of expectation the expectation of Xij is equal to the probability of the event “zi is compared to zj” =      ∑ ∑ − = += 1 1 1 n i n ij ijXE [ ]=∑ ∑ − = += 1 1 1 n i n ij ijXE ∑ ∑ − = += = 1 1 1 }Pr{ n i n ij ji ztocomparedisz indicator random variable
  • 8. 8 Comparisons in PARTITION : Observation 1 • Each pair of elements is compared at most once during the entire execution of the algorithm – Elements are compared only to the pivot point! – Pivot point is excluded from future calls to PARTITION
  • 9. 9 Comparisons in PARTITION: Observation 2 • Only the pivot is compared with elements in both partitions! z1z2 z9 z8 z5z3 z4 z6 z10 z7 106145389 72 Z1,6= {1, 2, 3, 4, 5, 6} Z8,9 = {8, 9, 10}{7} pivot Elements between different partitions are never compared!
  • 10. 10 Comparisons in PARTITION • Case 1: pivot chosen such as: zi < x < zj – zi and zj will never be compared • Case 2: zi or zj is the pivot – zi and zj will be compared – only if one of them is chosen as pivot before any other element in range zi to zj 106145389 72 z1z2 z9 z8 z5z3 z4 z6 z10 z7 Z1,6= {1, 2, 3, 4, 5, 6} Z8,9 = {8, 9, 10}{7} Pr{ }?i jz is compared to z
  • 11. 11 Probability of comparing zi with zj = 1/( j - i + 1) + 1/( j - i + 1) = 2/( j - i + 1) zi is compared to zj zi is the first pivot chosen from Zij =Pr{ } Pr{ } zj is the first pivot chosen from Zij Pr{ } OR+ •There are j – i + 1 elements between zi and zj – Pivot is chosen randomly and independently – The probability that any particular element is the first one chosen is 1/( j - i + 1)
  • 12. 12 Number of Comparisons in PARTITION 1 1 1 1 1 1 1 1 1 1 1 2 2 2 [ ] (lg ) 1 1 n n n n i n n n i j i i k i k i E X O n j i k k − − − − − = = + = = = = = = = < = − + + ∑ ∑ ∑∑ ∑∑ ∑ )lg( nnO= ⇒ Expected running time of Quicksort using RANDOMIZED-PARTITION is O(nlgn) ∑ ∑ − = += = 1 1 1 }Pr{][ n i n ij ji ztocomparediszXE Expected number of comparisons in PARTITION: (set k=j-i) (harmonic series)
  • 13. 13 Alternative Average-Case Analysis of Quicksort • See Problem 7-2, page 16 • Focus on the expected running time of each individual recursive call to Quicksort, rather than on the number of comparisons performed. • Use Hoare partition in our analysis.
  • 14. 14 Worst-Case Analysis T(n) = max (T(q) + T(n - q - 1)) + Θ(n) 0 ≤ q ≤ n-1 1.the time to sort the left partition with q elements, plus 2.the time to sort the right partition with N-q-1 elements, plus 3.the time to build the partitions where q ranges from 0 to n-1 since the procedure PARTITION produces two sub-problems with total size n-1 ---------- Substitution method: Guess T(n) ≤ cn2 T(n) ≤ max (cq2 + c(n - q - 1)2 ) + Θ(n) 0 ≤ q ≤ n-1 = c · max (q2 + (n - q - 1)2 ) + Θ(n) 0 ≤ q ≤ n-1 Take derivatives to get maximum at q = 0, n-1: T(n) ≤ c(n - 1)2 + Θ(n) ≤ cn2 - 2c(n - 1) + 1 + Θ(n) ≤ cn2 Therefore, the worst case running time is Θ(n2 )