SlideShare a Scribd company logo
Algorithms Analysis
Lecture 6
Quicksort
Quick Sort
88
14
9825
62
52
79
30
23
31
Divide and Conquer
Quick Sort
88
14
9825
62
52
79
30
23
31
Partition set into two using
randomly chosen pivot
14
25
30
2331
88
98
62
79
≤ 52 ≤
Quick Sort
14
25
30
2331
88
98
62
79
≤ 52 ≤
14,23,25,30,31
sort the first half.
62,79,98,88
sort the second half.
Quick Sort
14,23,25,30,31
62,79,88,98
52
Glue pieces together.
14,23,25,30,31,52,62,79,88,98
Quicksort
• Quicksort pros [advantage]:
– Sorts in place
– Sorts O(n lg n) in the average case
– Very efficient in practice , it’s quick
• Quicksort cons [disadvantage]:
– Sorts O(n2
) in the worst case
– And the worst case doesn’t happen often … sorted
Quicksort
• Another divide-and-conquer algorithm:
• Divide: A[p…r] is partitioned (rearranged) into two
nonempty subarrays A[p…q-1] and A[q+1…r] s.t.
each element of A[p…q-1] is less than or equal to
each element of A[q+1…r]. Index q is computed here,
called pivot.
• Conquer: two subarrays are sorted by recursive calls
to quicksort.
• Combine: unlike merge sort, no work needed since
the subarrays are sorted in place already.
Quicksort
• The basic algorithm to sort an array A consists of the following four
easy steps:
– If the number of elements in A is 0 or 1, then return
– Pick any element v in A. This is called the pivot
– Partition A-{v} (the remaining elements in A) into two disjoint
groups:
• A1 = {x ∈ A-{v} | x ≤ v}, and
• A2 = {x ∈ A-{v} | x ≥ v}
– return
• { quicksort(A1) followed by v followed by
quicksort(A2)}
Quicksort
• Small instance has n ≤ 1
– Every small instance is a sorted instance
• To sort a large instance:
– select a pivot element from out of the n elements
• Partition the n elements into 3 groups left, middle and
right
– The middle group contains only the pivot element
– All elements in the left group are ≤ pivot
– All elements in the right group are ≥ pivot
• Sort left and right groups recursively
• Answer is sorted left group, followed by middle group
followed by sorted right group
Quicksort Code
P: first element
r: last element
Quicksort(A, p, r)
{
if (p < r)
{
q = Partition(A, p, r)
Quicksort(A, p , q-1)
Quicksort(A, q+1 , r)
}
}
• Initial call is Quicksort(A, 1, n), where n in the length of A
Partition
• Clearly, all the action takes place in the
partition() function
– Rearranges the subarray in place
– End result:
• Two subarrays
• All values in first subarray ≤ all values in second
– Returns the index of the “pivot” element
separating the two subarrays
Partition Code
Partition(A, p, r)
{
x = A[r] // x is pivot
i = p - 1
for j = p to r – 1
{
do if A[j] <= x
then
{
i = i + 1
exchange A[i] ↔ A[j]
}
}
exchange A[i+1] ↔ A[r]
return i+1
}
partition() runs in O(n) time
Partition Example
A = {2, 8, 7, 1, 3, 5, 6, 4{
2 8 7 1 3 5 62 8 7 1 3 5 6 44
rp ji
2 8 7 1 3 5 62 8 7 1 3 5 6 44
rp i j
rp i j
2 8 7 1 3 5 62 8 7 1 3 5 6 44
rp i j
8822 77 11 33 55 66 44
rp j
1122 77 88 33 55 66 44
i rp j
1122 33 88 77 55 66 44
i
rp j
1122 33 88 77 55 66 44
i rp
1122 33 88 77 55 66 44
i
rp
1122 33 44 77 55 66 88
i
22
22
22 22
22 22
22
11
11 33
33 11 33
11 33
Partition Example Explanation
• Red shaded elements are in the first partition
with values ≤ x (pivot)
• Gray shaded elements are in the second
partition with values ≥ x (pivot)
• The unshaded elements have no yet been put in
one of the first two partitions
• The final white element is the pivot
Choice Of Pivot
Three ways to choose the pivot:
• Pivot is rightmost element in list that is to be sorted
– When sorting A[6:20], use A[20] as the pivot
– Textbook implementation does this
• Randomly select one of the elements to be sorted as
the pivot
– When sorting A[6:20], generate a random number r in
the range [6, 20]
– Use A[r] as the pivot
Choice Of Pivot
• Median-of-Three rule - from the leftmost, middle, and rightmost
elements of the list to be sorted, select the one with median key as
the pivot
– When sorting A[6:20], examine A[6], A[13] ((6+20)/2), and A[20]
– Select the element with median (i.e., middle) key
– If A[6].key = 30, A[13].key = 2, and A[20].key = 10, A[20]
becomes the pivot
– If A[6].key = 3, A[13].key = 2, and A[20].key = 10, A[6] becomes
the pivot
Worst Case Partitioning
• The running time of quicksort depends on whether the partitioning is
balanced or not.
∀ Θ(n) time to partition an array of n elements
• Let T(n) be the time needed to sort n elements
• T(0) = T(1) = c, where c is a constant
• When n > 1,
– T(n) = T(|left|) + T(|right|) + Θ(n)
• T(n) is maximum (worst-case) when either |left| = 0 or |right| = 0
following each partitioning
Worst Case Partitioning
Worst Case Partitioning
• Worst-Case Performance (unbalanced):
– T(n) = T(1) + T(n-1) + Θ(n)
• partitioning takes Θ(n)
= [2 + 3 + 4 + …+ n-1 + n ]+ n =
= [∑k = 2 to n k ]+ n = Θ(n2
)
• This occurs when
– the input is completely sorted
• or when
– the pivot is always the smallest (largest) element
)(2/)1(...21 2
1
nnnnk
n
k
Θ=+=+++=∑=
Best Case Partition
• When the partitioning procedure produces two regions of
size n/2, we get the a balanced partition with best case
performance:
– T(n) = 2T(n/2) + Θ(n) = Θ(n lg n)
• Average complexity is also Θ(n lg n)
Best Case Partitioning
Average Case
• Assuming random input, average-case running time is
much closer to Θ(n lg n) than Θ(n2
)
• First, a more intuitive explanation/example:
– Suppose that partition() always produces a 9-to-1
proportional split. This looks quite unbalanced!
– The recurrence is thus:
T(n) = T(9n/10) + T(n/10) + Θ(n) = Θ(nlg n)?
[Using recursion tree method to solve]
Average Case
( ) ( /10) (9 /10) ( ) ( log )!T n T n T n n n n= + + Θ = Θ
log2n = log10n/log102
Average Case
• Every level of the tree has cost cn, until a boundary condition
is reached at depth log10 n = Θ( lgn), and then the levels have
cost at most cn.
• The recursion terminates at depth log10/9 n= Θ(lg n).
• The total cost of quicksort is therefore O(n lg n).
Average Case
• What happens if we bad-split root node, then good-split
the resulting size (n-1) node?
– We end up with three subarrays, size
• 1, (n-1)/2, (n-1)/2
– Combined cost of splits = n + n-1 = 2n -1 = Θ(n)
n
1 n-1
(n-1)/2 (n-1)/2
( )nΘ
(n-1)/2 (n-1)/2
n ( )nΘ
)1( −Θ n
Intuition for the Average Case
• Suppose, we alternate lucky and unlucky cases to get
an average behavior
( ) 2 ( / 2) ( ) lucky
( ) ( 1) ( ) unlucky
we consequently get
( ) 2( ( / 2 1) ( / 2)) ( )
2 ( /2 1) ( )
( log )
L n U n n
U n L n n
L n L n n n
L n n
n n
= + Θ
= − + Θ
= − + Θ + Θ
= − + Θ
= Θ
The combination of good and bad splits would result in
T(n) = O (n lg n), but with slightly larger constant hidden by
the O-notation.
Randomized Quicksort
• An algorithm is randomized if its behavior is determined
not only by the input but also by values produced by a
random-number generator.
• Exchange A[r] with an element chosen at random from
A[p…r] in Partition.
• This ensures that the pivot element is equally likely to be
any of input elements.
• We can sometimes add randomization to an algorithm in
order to obtain good average-case performance over all
inputs.
Randomized Quicksort
Randomized-Partition(A, p, r)
1. i ← Random(p, r)
2. exchange A[r] ↔ A[i]
3. return Partition(A, p, r)
Randomized-Quicksort(A, p, r)
1. if p < r
2. then q ← Randomized-Partition(A, p, r)
3. Randomized-Quicksort(A, p , q-1)
4. Randomized-Quicksort(A, q+1, r)
pivot
swap
Review: Analyzing Quicksort
• What will be the worst case for the algorithm?
– Partition is always unbalanced
• What will be the best case for the algorithm?
– Partition is balanced
Summary: Quicksort
• In worst-case, efficiency is Θ(n2
)
– But easy to avoid the worst-case
• On average, efficiency is Θ(n lg n)
• Better space-complexity than mergesort.
• In practice, runs fast and widely used
Ad

More Related Content

What's hot (20)

Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Mohammed Hussein
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
District Administration
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
Masud Parvaze
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
Algorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIAlgorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms II
Mohamed Loey
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Pranay Neema
 
Binary search
Binary searchBinary search
Binary search
AparnaKumari31
 
I.BEST FIRST SEARCH IN AI
I.BEST FIRST SEARCH IN AII.BEST FIRST SEARCH IN AI
I.BEST FIRST SEARCH IN AI
vikas dhakane
 
Bit pair recoding
Bit pair recodingBit pair recoding
Bit pair recoding
Basit Ali
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
Mohd Arif
 
Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
Quick sort
Quick sortQuick sort
Quick sort
Afaq Mansoor Khan
 
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
Umesh Kumar
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
Mohamed Loey
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
Anuj Modi
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
vikas dhakane
 
Linked lists
Linked listsLinked lists
Linked lists
SARITHA REDDY
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
Balwant Gorad
 
Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)
Flynce Miguel
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
Himanshu Kesharwani
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
District Administration
 
Algorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIAlgorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms II
Mohamed Loey
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Pranay Neema
 
I.BEST FIRST SEARCH IN AI
I.BEST FIRST SEARCH IN AII.BEST FIRST SEARCH IN AI
I.BEST FIRST SEARCH IN AI
vikas dhakane
 
Bit pair recoding
Bit pair recodingBit pair recoding
Bit pair recoding
Basit Ali
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
Mohd Arif
 
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
Umesh Kumar
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
Mohamed Loey
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
Anuj Modi
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
vikas dhakane
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
Balwant Gorad
 
Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)
Flynce Miguel
 

Viewers also liked (12)

Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)
Jea Hyeun Jung
 
Lecture 6-cs648 Randomized Algorithms
Lecture 6-cs648 Randomized AlgorithmsLecture 6-cs648 Randomized Algorithms
Lecture 6-cs648 Randomized Algorithms
Anshul Yadav
 
Quick Sort
Quick SortQuick Sort
Quick Sort
priyankanaidu6
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
Mohammed Hussein
 
Quicksort: illustrated step-by-step walk through
Quicksort: illustrated step-by-step walk throughQuicksort: illustrated step-by-step walk through
Quicksort: illustrated step-by-step walk through
Yoshi Watanabe
 
Safe laparoscopy
Safe laparoscopySafe laparoscopy
Safe laparoscopy
Mamdouh Sabry
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
Madhu Bala
 
Insertion and merge sort
Insertion and merge sortInsertion and merge sort
Insertion and merge sort
Preetham Devisetty
 
Insertion Sort Algorithm
Insertion Sort AlgorithmInsertion Sort Algorithm
Insertion Sort Algorithm
Gail Carmichael
 
3.8 quicksort
3.8 quicksort3.8 quicksort
3.8 quicksort
Krish_ver2
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
Lovely Professional University
 
Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)
Jea Hyeun Jung
 
Lecture 6-cs648 Randomized Algorithms
Lecture 6-cs648 Randomized AlgorithmsLecture 6-cs648 Randomized Algorithms
Lecture 6-cs648 Randomized Algorithms
Anshul Yadav
 
Quick Sort , Merge Sort , Heap Sort
Quick Sort , Merge Sort ,  Heap SortQuick Sort , Merge Sort ,  Heap Sort
Quick Sort , Merge Sort , Heap Sort
Mohammed Hussein
 
Quicksort: illustrated step-by-step walk through
Quicksort: illustrated step-by-step walk throughQuicksort: illustrated step-by-step walk through
Quicksort: illustrated step-by-step walk through
Yoshi Watanabe
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
Madhu Bala
 
Insertion Sort Algorithm
Insertion Sort AlgorithmInsertion Sort Algorithm
Insertion Sort Algorithm
Gail Carmichael
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Ad

Similar to Quick sort Algorithm Discussion And Analysis (20)

Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2
Deepak John
 
Quick Sort
Quick SortQuick Sort
Quick Sort
Soumen Santra
 
DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024
RUHULAMINHAZARIKA
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
Shiwani Gupta
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
Dr. C.V. Suresh Babu
 
Sorting algorithms bubble sort to merge sort.pdf
Sorting  algorithms bubble sort to merge sort.pdfSorting  algorithms bubble sort to merge sort.pdf
Sorting algorithms bubble sort to merge sort.pdf
AyeshaMazhar21
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptx
DeepakM509554
 
09 QUICK SORT Design and Analysis of algorithms
09 QUICK SORT Design and Analysis of algorithms09 QUICK SORT Design and Analysis of algorithms
09 QUICK SORT Design and Analysis of algorithms
syamalamaganti
 
Quick sort
Quick sortQuick sort
Quick sort
Dhruv Sabalpara
 
03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt
vanshii9976
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
DeepakM509554
 
Divide and Conquer in DAA concept. For B Tech CSE
Divide and Conquer  in DAA concept. For B Tech CSEDivide and Conquer  in DAA concept. For B Tech CSE
Divide and Conquer in DAA concept. For B Tech CSE
RUHULAMINHAZARIKA
 
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
Humano Terricola
 
Sorting
SortingSorting
Sorting
Gopi Saiteja
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito86
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
Ummar Hayat
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)
Kamal Singh Lodhi
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
zukun
 
07 Analysis of Algorithms: Order Statistics
07 Analysis of Algorithms: Order Statistics07 Analysis of Algorithms: Order Statistics
07 Analysis of Algorithms: Order Statistics
Andres Mendez-Vazquez
 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2
Deepak John
 
DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024
RUHULAMINHAZARIKA
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
Shiwani Gupta
 
Sorting algorithms bubble sort to merge sort.pdf
Sorting  algorithms bubble sort to merge sort.pdfSorting  algorithms bubble sort to merge sort.pdf
Sorting algorithms bubble sort to merge sort.pdf
AyeshaMazhar21
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptx
DeepakM509554
 
09 QUICK SORT Design and Analysis of algorithms
09 QUICK SORT Design and Analysis of algorithms09 QUICK SORT Design and Analysis of algorithms
09 QUICK SORT Design and Analysis of algorithms
syamalamaganti
 
03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt
vanshii9976
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
DeepakM509554
 
Divide and Conquer in DAA concept. For B Tech CSE
Divide and Conquer  in DAA concept. For B Tech CSEDivide and Conquer  in DAA concept. For B Tech CSE
Divide and Conquer in DAA concept. For B Tech CSE
RUHULAMINHAZARIKA
 
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
Humano Terricola
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito86
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
Ummar Hayat
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
zukun
 
07 Analysis of Algorithms: Order Statistics
07 Analysis of Algorithms: Order Statistics07 Analysis of Algorithms: Order Statistics
07 Analysis of Algorithms: Order Statistics
Andres Mendez-Vazquez
 
Ad

Recently uploaded (20)

6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink DisplayHow to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
CircuitDigest
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation RateModeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Journal of Soft Computing in Civil Engineering
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink DisplayHow to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
CircuitDigest
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 

Quick sort Algorithm Discussion And Analysis

  • 3. Quick Sort 88 14 9825 62 52 79 30 23 31 Partition set into two using randomly chosen pivot 14 25 30 2331 88 98 62 79 ≤ 52 ≤
  • 4. Quick Sort 14 25 30 2331 88 98 62 79 ≤ 52 ≤ 14,23,25,30,31 sort the first half. 62,79,98,88 sort the second half.
  • 5. Quick Sort 14,23,25,30,31 62,79,88,98 52 Glue pieces together. 14,23,25,30,31,52,62,79,88,98
  • 6. Quicksort • Quicksort pros [advantage]: – Sorts in place – Sorts O(n lg n) in the average case – Very efficient in practice , it’s quick • Quicksort cons [disadvantage]: – Sorts O(n2 ) in the worst case – And the worst case doesn’t happen often … sorted
  • 7. Quicksort • Another divide-and-conquer algorithm: • Divide: A[p…r] is partitioned (rearranged) into two nonempty subarrays A[p…q-1] and A[q+1…r] s.t. each element of A[p…q-1] is less than or equal to each element of A[q+1…r]. Index q is computed here, called pivot. • Conquer: two subarrays are sorted by recursive calls to quicksort. • Combine: unlike merge sort, no work needed since the subarrays are sorted in place already.
  • 8. Quicksort • The basic algorithm to sort an array A consists of the following four easy steps: – If the number of elements in A is 0 or 1, then return – Pick any element v in A. This is called the pivot – Partition A-{v} (the remaining elements in A) into two disjoint groups: • A1 = {x ∈ A-{v} | x ≤ v}, and • A2 = {x ∈ A-{v} | x ≥ v} – return • { quicksort(A1) followed by v followed by quicksort(A2)}
  • 9. Quicksort • Small instance has n ≤ 1 – Every small instance is a sorted instance • To sort a large instance: – select a pivot element from out of the n elements • Partition the n elements into 3 groups left, middle and right – The middle group contains only the pivot element – All elements in the left group are ≤ pivot – All elements in the right group are ≥ pivot • Sort left and right groups recursively • Answer is sorted left group, followed by middle group followed by sorted right group
  • 10. Quicksort Code P: first element r: last element Quicksort(A, p, r) { if (p < r) { q = Partition(A, p, r) Quicksort(A, p , q-1) Quicksort(A, q+1 , r) } } • Initial call is Quicksort(A, 1, n), where n in the length of A
  • 11. Partition • Clearly, all the action takes place in the partition() function – Rearranges the subarray in place – End result: • Two subarrays • All values in first subarray ≤ all values in second – Returns the index of the “pivot” element separating the two subarrays
  • 12. Partition Code Partition(A, p, r) { x = A[r] // x is pivot i = p - 1 for j = p to r – 1 { do if A[j] <= x then { i = i + 1 exchange A[i] ↔ A[j] } } exchange A[i+1] ↔ A[r] return i+1 } partition() runs in O(n) time
  • 13. Partition Example A = {2, 8, 7, 1, 3, 5, 6, 4{ 2 8 7 1 3 5 62 8 7 1 3 5 6 44 rp ji 2 8 7 1 3 5 62 8 7 1 3 5 6 44 rp i j rp i j 2 8 7 1 3 5 62 8 7 1 3 5 6 44 rp i j 8822 77 11 33 55 66 44 rp j 1122 77 88 33 55 66 44 i rp j 1122 33 88 77 55 66 44 i rp j 1122 33 88 77 55 66 44 i rp 1122 33 88 77 55 66 44 i rp 1122 33 44 77 55 66 88 i 22 22 22 22 22 22 22 11 11 33 33 11 33 11 33
  • 14. Partition Example Explanation • Red shaded elements are in the first partition with values ≤ x (pivot) • Gray shaded elements are in the second partition with values ≥ x (pivot) • The unshaded elements have no yet been put in one of the first two partitions • The final white element is the pivot
  • 15. Choice Of Pivot Three ways to choose the pivot: • Pivot is rightmost element in list that is to be sorted – When sorting A[6:20], use A[20] as the pivot – Textbook implementation does this • Randomly select one of the elements to be sorted as the pivot – When sorting A[6:20], generate a random number r in the range [6, 20] – Use A[r] as the pivot
  • 16. Choice Of Pivot • Median-of-Three rule - from the leftmost, middle, and rightmost elements of the list to be sorted, select the one with median key as the pivot – When sorting A[6:20], examine A[6], A[13] ((6+20)/2), and A[20] – Select the element with median (i.e., middle) key – If A[6].key = 30, A[13].key = 2, and A[20].key = 10, A[20] becomes the pivot – If A[6].key = 3, A[13].key = 2, and A[20].key = 10, A[6] becomes the pivot
  • 17. Worst Case Partitioning • The running time of quicksort depends on whether the partitioning is balanced or not. ∀ Θ(n) time to partition an array of n elements • Let T(n) be the time needed to sort n elements • T(0) = T(1) = c, where c is a constant • When n > 1, – T(n) = T(|left|) + T(|right|) + Θ(n) • T(n) is maximum (worst-case) when either |left| = 0 or |right| = 0 following each partitioning
  • 19. Worst Case Partitioning • Worst-Case Performance (unbalanced): – T(n) = T(1) + T(n-1) + Θ(n) • partitioning takes Θ(n) = [2 + 3 + 4 + …+ n-1 + n ]+ n = = [∑k = 2 to n k ]+ n = Θ(n2 ) • This occurs when – the input is completely sorted • or when – the pivot is always the smallest (largest) element )(2/)1(...21 2 1 nnnnk n k Θ=+=+++=∑=
  • 20. Best Case Partition • When the partitioning procedure produces two regions of size n/2, we get the a balanced partition with best case performance: – T(n) = 2T(n/2) + Θ(n) = Θ(n lg n) • Average complexity is also Θ(n lg n)
  • 22. Average Case • Assuming random input, average-case running time is much closer to Θ(n lg n) than Θ(n2 ) • First, a more intuitive explanation/example: – Suppose that partition() always produces a 9-to-1 proportional split. This looks quite unbalanced! – The recurrence is thus: T(n) = T(9n/10) + T(n/10) + Θ(n) = Θ(nlg n)? [Using recursion tree method to solve]
  • 23. Average Case ( ) ( /10) (9 /10) ( ) ( log )!T n T n T n n n n= + + Θ = Θ log2n = log10n/log102
  • 24. Average Case • Every level of the tree has cost cn, until a boundary condition is reached at depth log10 n = Θ( lgn), and then the levels have cost at most cn. • The recursion terminates at depth log10/9 n= Θ(lg n). • The total cost of quicksort is therefore O(n lg n).
  • 25. Average Case • What happens if we bad-split root node, then good-split the resulting size (n-1) node? – We end up with three subarrays, size • 1, (n-1)/2, (n-1)/2 – Combined cost of splits = n + n-1 = 2n -1 = Θ(n) n 1 n-1 (n-1)/2 (n-1)/2 ( )nΘ (n-1)/2 (n-1)/2 n ( )nΘ )1( −Θ n
  • 26. Intuition for the Average Case • Suppose, we alternate lucky and unlucky cases to get an average behavior ( ) 2 ( / 2) ( ) lucky ( ) ( 1) ( ) unlucky we consequently get ( ) 2( ( / 2 1) ( / 2)) ( ) 2 ( /2 1) ( ) ( log ) L n U n n U n L n n L n L n n n L n n n n = + Θ = − + Θ = − + Θ + Θ = − + Θ = Θ The combination of good and bad splits would result in T(n) = O (n lg n), but with slightly larger constant hidden by the O-notation.
  • 27. Randomized Quicksort • An algorithm is randomized if its behavior is determined not only by the input but also by values produced by a random-number generator. • Exchange A[r] with an element chosen at random from A[p…r] in Partition. • This ensures that the pivot element is equally likely to be any of input elements. • We can sometimes add randomization to an algorithm in order to obtain good average-case performance over all inputs.
  • 28. Randomized Quicksort Randomized-Partition(A, p, r) 1. i ← Random(p, r) 2. exchange A[r] ↔ A[i] 3. return Partition(A, p, r) Randomized-Quicksort(A, p, r) 1. if p < r 2. then q ← Randomized-Partition(A, p, r) 3. Randomized-Quicksort(A, p , q-1) 4. Randomized-Quicksort(A, q+1, r) pivot swap
  • 29. Review: Analyzing Quicksort • What will be the worst case for the algorithm? – Partition is always unbalanced • What will be the best case for the algorithm? – Partition is balanced
  • 30. Summary: Quicksort • In worst-case, efficiency is Θ(n2 ) – But easy to avoid the worst-case • On average, efficiency is Θ(n lg n) • Better space-complexity than mergesort. • In practice, runs fast and widely used

Editor's Notes

  • #27: larger constant in the O notation
  翻译: