SlideShare a Scribd company logo
1 of 19
Quick Sort
Afaq Mansoor Khan
BSSE 2017-21
IMSciences Peshawar
What is Quick Sort?
• Quick sort is a divide and conquer algorithm
which relies on a partition operation:
– to partition an array an element called a pivot is
selected
• All elements smaller than the pivot are moved
before it and all greater elements are moved
after it
• The lesser and greater sublists are then
recursively sorted
2
Quick sort
• Efficient implementations (with in-place
partitioning), somewhat complex, but are
among the fastest sorting algorithms in
practice
• One of the most popular sorting algorithms
and is available in many standard
programming libraries.
Idea of Quick-Sort
1) Divide : If the sequence S has 2 or more elements,
select an element x from S to be your pivot. Any
arbitrary element, like the last, will do. Remove all the
elements of S and divide them into 3 sequences:
L, holds S’s elements less than x
E, holds S’s elements equal to x
G, holds S’s elements greater than x
2) Recurse: Recursively sort L and G
3) Conquer: Finally, to put elements back into S in order,
first inserts the elements of L, then those of E, and
those of G.
Idea of Quick Sort
1) Select: pick an element
2) Divide: rearrange elements so
that x goes to its final position E
3) Recurse and Conquer:
recursively sort
Two key steps
• How to pick a pivot?
• How to partition?
Pick a pivot
• Use the first element as pivot
– if the input is random, ok
– if the input is presorted (or in reverse order)
• all the elements go into S2 (or S1)
• Results in O(n2) behavior (Analyze this case later)
• Choose the pivot randomly
– generally safe
A better partition
• Want to partition an array A[left .. right]
• First, get the pivot element out of the way by swapping it with the last
element. (Swap pivot and A[right])
pivot i j
5 6 4 6 3 12 19 5 6 4 63 1219
swap
– Move i right, skipping over elements smaller than the
pivot
– Move j left, skipping over elements greater than the pivot
i j
5 6 4 63 1219
i j
5 6 4 63 1219
• When i and j have stopped and i is to the left of j
– Swap A[i] and A[j]
• The large element is pushed to the right and the small element is pushed to
the left
– Repeat the process until i and j cross
swap
i j
5 6 4 63 1219
i j
5 3 4 66 1219
• When i and j have crossed
– Swap A[i] and pivot
• Result:
– A[x] <= pivot, for x < i
– A[x] >= pivot, for x > i
i j
5 3 4 66 1219
ij
5 3 4 66 1219
ij
5 3 4 6 6 12 19
Quicksort example
1
3
8
1
9
2
4
3
3
1
6
5
5
7
2
6
7
5
0
1
3
8
1
9
2
4
3
3
1
6
5
5
7
2
6
7
5
0
1
3 4
3
3
1
5
72
6
0
8
1
9
2
7
5
6
5
1
3
4
3
3
1
5
7
2
6
0
8
1
9
2
7
5
1
3
4
3
3
1
5
7
2
6
0
6
5
8
1
9
2
7
5
Select pivot
partition
Recursive call Recursive call
Merge
Quicksort Algorithm
• To sort a[left...right]:
1. if left < right:
1.1. Partition a[left...right] such that:
all a[left...p-1] are less than a[p], and
all a[p+1...right] are >= a[p]
1.2. Quicksort a[left...p-1]
1.3. Quicksort a[p+1...right]
2. Terminate
Quick Sort Source Code C++
void QuickSort(int list[], int left, int right) {
int pivot, leftArrow, rightArrow;
leftArrow = left;
rightArrow = right;
pivot = list[(left + right) / 2];
do {
while (list[rightArrow] > pivot)
rightArrow--;
while (list[leftArrow] < pivot)
leftArrow++;
if (leftArrow <= rightArrow) {
Swap_Data(list[leftArrow], list[rightArrow]);
leftArrow++;
rightArrow--;
}
}
while (rightArrow >= leftArrow);
if (left < rightArrow)
QuickSort(list, left, rightArrow);
if (leftArrow < right)
QuickSort(list, leftArrow, right);
}
Quick Sort Pseudo Code
• QuickSort(A,start,end)
• { if(start<end)
• { pIndex 🡨 partition(A,start,end)
QuickSort(A,start,Pindex-1)
QuickSort(A,Pindex+1,end)
}
}
• Partition(A,start,end)
• { pivot 🡨 A[end]
Pindex 🡨 start
For i 🡨 start to end-1
{
If(A[i] <= pivot)
{ Swap(a[i],P[pindex])
Pindex 🡨 Pindex+1
}
}
Swap(A[pindex] , A[end])
Return Pindex }
Complexity of Quick Sort
• Best case performance O(n log n)
• Average case performance O(n log n)
• Worst case performance O(n2)
• Worst case space complexity auxiliary O(log n)
• Where n is the number of elements to be sorted
Questions?
THANK YOU!
☺
References
• Data Structures and Algorithm Analysis by M. A.
Weiss, 2nd edition
• https://cs.nyu.edu/courses/spring99/V22.0102-
002/quick.html
• www.dcs.gla.ac.uk/~pat/52233/slides/QuickSort1x1.
pdf

More Related Content

What's hot (20)

Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Queues
QueuesQueues
Queues
 
Page replacement algorithms
Page replacement algorithmsPage replacement algorithms
Page replacement algorithms
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
 
Quick sort
Quick sortQuick sort
Quick sort
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching Algorithms
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 
Linked list
Linked listLinked list
Linked list
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
 
linked list
linked list linked list
linked list
 
Ppt bubble sort
Ppt bubble sortPpt bubble sort
Ppt bubble sort
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Sorting
SortingSorting
Sorting
 
Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSA
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 

Similar to Quick sort

quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptxDeepakM509554
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sortKrish_ver2
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisRadhika Talaviya
 
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
 
Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Mahesh Tibrewal
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisSNJ Chaudhary
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptxParagAhir1
 

Similar to Quick sort (20)

s4_quick_sort.ppt
s4_quick_sort.ppts4_quick_sort.ppt
s4_quick_sort.ppt
 
Quick sort.pptx
Quick sort.pptxQuick sort.pptx
Quick sort.pptx
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
 
Sorting
SortingSorting
Sorting
 
Algorithms - "quicksort"
Algorithms - "quicksort"Algorithms - "quicksort"
Algorithms - "quicksort"
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 
quicksort (1).ppt
quicksort (1).pptquicksort (1).ppt
quicksort (1).ppt
 
Data Structure Sorting
Data Structure SortingData Structure Sorting
Data Structure Sorting
 
Quick sort algorithm
Quick sort algorithmQuick sort algorithm
Quick sort algorithm
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
 
CSPC/ PPS Sorting methods
CSPC/ PPS Sorting methodsCSPC/ PPS Sorting methods
CSPC/ PPS Sorting methods
 
Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)
 
Sortings .pptx
Sortings .pptxSortings .pptx
Sortings .pptx
 
Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!Quicksort Algorithm..simply defined through animations..!!
Quicksort Algorithm..simply defined through animations..!!
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And Analysis
 
Bs,qs,divide and conquer 1
Bs,qs,divide and conquer 1Bs,qs,divide and conquer 1
Bs,qs,divide and conquer 1
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 

More from Afaq Mansoor Khan

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingAfaq Mansoor Khan
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in PakistanAfaq Mansoor Khan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAfaq Mansoor Khan
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An OverviewAfaq Mansoor Khan
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design DecisionsAfaq Mansoor Khan
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinAfaq Mansoor Khan
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - AsteroidsAfaq Mansoor Khan
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & DeletionAfaq Mansoor Khan
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked ListsAfaq Mansoor Khan
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 

More from Afaq Mansoor Khan (20)

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language Processing
 
WiFi vs LiFi - A Comparison
WiFi vs LiFi - A ComparisonWiFi vs LiFi - A Comparison
WiFi vs LiFi - A Comparison
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in Pakistan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and Strategies
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An Overview
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design Decisions
 
How to Design an Algorithm
How to Design an AlgorithmHow to Design an Algorithm
How to Design an Algorithm
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and Linkedin
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - Asteroids
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Binary tree
Binary treeBinary tree
Binary tree
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked Lists
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 

Recently uploaded

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 

Recently uploaded (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 

Quick sort

  • 1. Quick Sort Afaq Mansoor Khan BSSE 2017-21 IMSciences Peshawar
  • 2. What is Quick Sort? • Quick sort is a divide and conquer algorithm which relies on a partition operation: – to partition an array an element called a pivot is selected • All elements smaller than the pivot are moved before it and all greater elements are moved after it • The lesser and greater sublists are then recursively sorted 2
  • 3. Quick sort • Efficient implementations (with in-place partitioning), somewhat complex, but are among the fastest sorting algorithms in practice • One of the most popular sorting algorithms and is available in many standard programming libraries.
  • 4. Idea of Quick-Sort 1) Divide : If the sequence S has 2 or more elements, select an element x from S to be your pivot. Any arbitrary element, like the last, will do. Remove all the elements of S and divide them into 3 sequences: L, holds S’s elements less than x E, holds S’s elements equal to x G, holds S’s elements greater than x 2) Recurse: Recursively sort L and G 3) Conquer: Finally, to put elements back into S in order, first inserts the elements of L, then those of E, and those of G.
  • 5. Idea of Quick Sort 1) Select: pick an element 2) Divide: rearrange elements so that x goes to its final position E 3) Recurse and Conquer: recursively sort
  • 6. Two key steps • How to pick a pivot? • How to partition?
  • 7. Pick a pivot • Use the first element as pivot – if the input is random, ok – if the input is presorted (or in reverse order) • all the elements go into S2 (or S1) • Results in O(n2) behavior (Analyze this case later) • Choose the pivot randomly – generally safe
  • 8. A better partition • Want to partition an array A[left .. right] • First, get the pivot element out of the way by swapping it with the last element. (Swap pivot and A[right]) pivot i j 5 6 4 6 3 12 19 5 6 4 63 1219 swap
  • 9. – Move i right, skipping over elements smaller than the pivot – Move j left, skipping over elements greater than the pivot i j 5 6 4 63 1219 i j 5 6 4 63 1219
  • 10. • When i and j have stopped and i is to the left of j – Swap A[i] and A[j] • The large element is pushed to the right and the small element is pushed to the left – Repeat the process until i and j cross swap i j 5 6 4 63 1219 i j 5 3 4 66 1219
  • 11. • When i and j have crossed – Swap A[i] and pivot • Result: – A[x] <= pivot, for x < i – A[x] >= pivot, for x > i i j 5 3 4 66 1219 ij 5 3 4 66 1219 ij 5 3 4 6 6 12 19
  • 13. Quicksort Algorithm • To sort a[left...right]: 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and all a[p+1...right] are >= a[p] 1.2. Quicksort a[left...p-1] 1.3. Quicksort a[p+1...right] 2. Terminate
  • 14. Quick Sort Source Code C++ void QuickSort(int list[], int left, int right) { int pivot, leftArrow, rightArrow; leftArrow = left; rightArrow = right; pivot = list[(left + right) / 2]; do { while (list[rightArrow] > pivot) rightArrow--; while (list[leftArrow] < pivot) leftArrow++; if (leftArrow <= rightArrow) { Swap_Data(list[leftArrow], list[rightArrow]); leftArrow++; rightArrow--; } } while (rightArrow >= leftArrow); if (left < rightArrow) QuickSort(list, left, rightArrow); if (leftArrow < right) QuickSort(list, leftArrow, right); }
  • 15. Quick Sort Pseudo Code • QuickSort(A,start,end) • { if(start<end) • { pIndex 🡨 partition(A,start,end) QuickSort(A,start,Pindex-1) QuickSort(A,Pindex+1,end) } } • Partition(A,start,end) • { pivot 🡨 A[end] Pindex 🡨 start For i 🡨 start to end-1 { If(A[i] <= pivot) { Swap(a[i],P[pindex]) Pindex 🡨 Pindex+1 } } Swap(A[pindex] , A[end]) Return Pindex }
  • 16. Complexity of Quick Sort • Best case performance O(n log n) • Average case performance O(n log n) • Worst case performance O(n2) • Worst case space complexity auxiliary O(log n) • Where n is the number of elements to be sorted
  • 19. References • Data Structures and Algorithm Analysis by M. A. Weiss, 2nd edition • https://cs.nyu.edu/courses/spring99/V22.0102- 002/quick.html • www.dcs.gla.ac.uk/~pat/52233/slides/QuickSort1x1. pdf