SlideShare a Scribd company logo
1 of 25
Placement Preparation 
Sorting and Heaps 
Varun Raj 
B.Tech, CSE
Prerequisites 
• You must know array properly. 
• You must be familiar with pointers and writing basic 
loops 
• You must have some basic idea of time complexity
Aim of Lecture 
● Selection Sort/Bubble Sort 
● Insertion Sort 
● Merge Sort 
● Heaps and Heapsort 
● Quick Sort (If possible)
Motivation 
Sorting is any process of arranging items according to value. 
In computer science, sorting is one of the most extensively 
researched subjects because of the need to speed up the operation 
on thousands or millions of records during a search operation
The real reason. 
● The real reason we are studying sorting is because be 
it any coding question in any interview the candidate 
is expected to know the basic of the sorting and 
sorting questions are the most expected questions to 
be asked
Selection Sort 
The most intuitive sorting algorithm. 
Works by selecting the smallest element of the 
array and placing it at the head of the array. 
Then the process is repeated for the remainder 
of the array the next smallest element is 
selected and put into the next slot, and so on 
down the line
Demo #1 
Code of Selection Sort
Exercise #1 
● Write a program that does selection sort on a set of 
integers 
● Some pointers- 
● You will need two loops 
● You will need a variable that stores the current 
minimum and then you will have to swap it with the 
head.
Analysing Complexity 
• In the 1st step the algorithm the for loop runs n-1 
times. 
• In the second step the for loop runs n-2 times since the 
1st element is set 
• Hence the time taken is n-1+n-2+n-3……..+1=n*(n-1)/2 
That is O(n^2) 
• The thing to note is that the complexity is O(n^2) for 
best, average and worst case. 
• The space complexity is O(1) that is no extra space is 
used since the algorithm works only on the input array
Bubble Sort 
The bubble sort works by iterating 
down an array to be sorted from the 
first element to the last, comparing 
each pair of elements and switching 
their positions if necessary. This 
process is repeated as many times as 
necessary, until the array is sorted
Demo #2 
Code For Bubble Sort
Exercise #2 
● Write a program that does bubble sort on a set of 
integers 
● Some pointers- 
● You will need two loops 
• At the end of 1st step the maximum reaches the last 
position .At the end of second step the 2nd maximum 
reaches the 2nd last position
Analysing Complexity for Bubble Sort 
• In the 1st step the algorithm the for loop runs n times. 
• In the second step the for loop runs n-1 times since the 
1st element is set 
• Hence the time taken is n+n-1+n-2……..+1=n*(n+1)/2 
That is O(n^2) 
• The thing to note is that the complexity is O(n^2) for 
best, average and worst case. 
• The space complexity is O(1) that is no extra space is 
used since the algorithm works only on the input array
Some Improvements To Bubble Sort 
On Close Observation we observe that even in the best 
case Bubble Sort takes O(n^2) time this can be reduced to 
O(n) that is in a perfectly sorted array bubble sort will 
only take O(n) time to terminate(which is already sorted) 
The idea behind this is that at each outer loop iteration 
keep a counter so that if in it’s inner loop iteration no 
swapping was done this means that the array is already 
sorted and no further outer loop iterations need to be 
done and the array is sorted.So terminate the code
Demo #3 
● This improves only the best case running time of bubble sort the 
worst case still remains O(n^2) 
● The complexity is O(n^2) for average and worst case. 
● For best case complexity is O(n) that is already sorted array
Insertion Sort 
It inserts each element of the array 
into its proper position, leaving 
progressively larger stretches of the 
array sorted
Demo 
Code for insertion sort
Analysing Complexity for Insertion 
Sort 
• In the 1st step the algorithm the for loop runs 0 times. 
• In the second step the for loop runs 1 times (worst 
case) Hence the time taken is 1+2+3….n-1=n*(n-1)/2 
That is O(n^2) (worst case) 
• The thing to note is that the complexity is O(n^2) for 
average and worst case. 
• The best case time complexity is O(n). 
• The space complexity is O(1) that is no extra space is 
used since the algorithm works only on the input array
Merge Sort 
MergeSort is a Divide and 
Conquer algorithm. It divides input array in 
two halves, calls itself recursively for the 
two halves and then merges the two sorted 
halves.
Merge Sort-Intiution 
The main concept here is 
recursion 
The Merge Sort takes an 
array from 1 to n and calls 
itself on the array [1,n/2] 
and [n/2+1,n] recursively 
both these subparts are 
sorted so too sort two 
completely sorted list we 
only merge them
Demo 
Code for merge sort 
Its little complicated so I would like you to practise 
properly 
Some common errors 
• Base case of recursion 
• Problems with merging especially when one half 
crosses the midpoint (Explained)
Analysing Complexity for Merging 
Sort 
• There is some trick involved in finding the time complexity of 
Merge Sort . The time complexity is O(nlogn) Here log refers to 
base 2. 
• Proof- 
• T(n)=2*T(n/2) +cn where c is any constant 
• The solution to this equation is k*nlogn the proof follows from 
substitution and something you can look up online or I can do on 
the board. 
• The space complexity of this algorithm is O(n) since we are using 
an extra array
Some remarks about Merge Sort 
• Merge Sort is the fastest algorithm you have seen till now.Its 
complexity is O(n*logn) and for large n it is faster than any 
quadratic algorithm for large input 
• Sometimes for small input merge sort may become slower than 
insertion sort due to constant factors.Hence for small input prefer 
insertion sort 
• The space complexity is O(n) that is an extra array is required this 
is the price we had to pay for a faster algorithm. 
• We will see now that Heaps offer us time complexity of O(nlogn) 
with no extra space required but it has a little sophisticated code.
Some Concluding Remarks - 
● We learnt 3 quadratic time sorting algorithms –Selection Sort, 
Insertion Sort, Bubble Sort 
● We learnt to optimise bubble sort for best case 
● The general advice is that whenever using a quadratic time 
algorithm use insertion sort. (The reason for this is given as an 
exercise at the last slide) 
● Merge Sort trumps all the algorithm given large enough input, 
however for input as small as 10 insertion sort will be faster
Extra Questions 
I am not going to discuss the answer to these questions in the class, 
however you could ask this question on facebook group or personally 
message me. 
These questions are for personal enhancement , maybe you could 
encounter this question in the placement interview/test maybe not 
• Insertion Sort-Prove that the time complexity of insertion sort is 
O(n+x) where x is the number of inversions in the input array.Here 
inversion refers to the pair (ai, aj) with i<j but ai >aj. 
• Merge Sort- The time complexity of Merge Sort is O(nlogn) .Prove 
that no sorting algorithm in the world that uses comparision 
sorting can be asymptotically faster than this

More Related Content

What's hot

Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Deepak John
 
Algorithms lecture 3
Algorithms lecture 3Algorithms lecture 3
Algorithms lecture 3Mimi Haque
 
01 Analysis of Algorithms: Introduction
01 Analysis of Algorithms: Introduction01 Analysis of Algorithms: Introduction
01 Analysis of Algorithms: IntroductionAndres Mendez-Vazquez
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to AlgorithmsVenkatesh Iyer
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmTarikuDabala1
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMSTanya Makkar
 
Basic terminologies & asymptotic notations
Basic terminologies & asymptotic notationsBasic terminologies & asymptotic notations
Basic terminologies & asymptotic notationsRajendran
 
Intro to Sorting + Insertion Sort
Intro to Sorting + Insertion SortIntro to Sorting + Insertion Sort
Intro to Sorting + Insertion SortNicholas Case
 
Fundamental computing algorithms
Fundamental computing algorithmsFundamental computing algorithms
Fundamental computing algorithmsGanesh Solanke
 
how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihmSajid Marwat
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Algorithm And analysis Lecture 03& 04-time complexity.
 Algorithm And analysis Lecture 03& 04-time complexity. Algorithm And analysis Lecture 03& 04-time complexity.
Algorithm And analysis Lecture 03& 04-time complexity.Tariq Khan
 
Algorithm Analyzing
Algorithm AnalyzingAlgorithm Analyzing
Algorithm AnalyzingHaluan Irsad
 

What's hot (20)

Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 
Algorithms lecture 3
Algorithms lecture 3Algorithms lecture 3
Algorithms lecture 3
 
Complexity of Algorithm
Complexity of AlgorithmComplexity of Algorithm
Complexity of Algorithm
 
01 Analysis of Algorithms: Introduction
01 Analysis of Algorithms: Introduction01 Analysis of Algorithms: Introduction
01 Analysis of Algorithms: Introduction
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Cupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithmCupdf.com introduction to-data-structures-and-algorithm
Cupdf.com introduction to-data-structures-and-algorithm
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Basic terminologies & asymptotic notations
Basic terminologies & asymptotic notationsBasic terminologies & asymptotic notations
Basic terminologies & asymptotic notations
 
Intro to Sorting + Insertion Sort
Intro to Sorting + Insertion SortIntro to Sorting + Insertion Sort
Intro to Sorting + Insertion Sort
 
Fundamental computing algorithms
Fundamental computing algorithmsFundamental computing algorithms
Fundamental computing algorithms
 
Unit 1
Unit 1Unit 1
Unit 1
 
how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihm
 
3 recursion
3 recursion3 recursion
3 recursion
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Design & Analysis Of Algorithm
Design & Analysis Of AlgorithmDesign & Analysis Of Algorithm
Design & Analysis Of Algorithm
 
Algorithm And analysis Lecture 03& 04-time complexity.
 Algorithm And analysis Lecture 03& 04-time complexity. Algorithm And analysis Lecture 03& 04-time complexity.
Algorithm And analysis Lecture 03& 04-time complexity.
 
Algorithm Analyzing
Algorithm AnalyzingAlgorithm Analyzing
Algorithm Analyzing
 

Similar to Lecture 11.2 : sorting

Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfAkashSingh625550
 
Algorithms & Complexity Calculation
Algorithms & Complexity CalculationAlgorithms & Complexity Calculation
Algorithms & Complexity CalculationAkhil Kaushik
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting AlgorithmsPranay Neema
 
shell and merge sort
shell and merge sortshell and merge sort
shell and merge sorti i
 
Lecture 2 data structures & algorithms - sorting techniques
Lecture 2  data structures & algorithms - sorting techniquesLecture 2  data structures & algorithms - sorting techniques
Lecture 2 data structures & algorithms - sorting techniquesDharmendra Prasad
 
Data Structure & Algorithms - Mathematical
Data Structure & Algorithms - MathematicalData Structure & Algorithms - Mathematical
Data Structure & Algorithms - Mathematicalbabuk110
 
Lecture 4 asymptotic notations
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notationsjayavignesh86
 
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...2022cspaawan12556
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmEhsan Ehrari
 
Lecture 3 insertion sort and complexity analysis
Lecture 3   insertion sort and complexity analysisLecture 3   insertion sort and complexity analysis
Lecture 3 insertion sort and complexity analysisjayavignesh86
 
9.Sorting & Searching
9.Sorting & Searching9.Sorting & Searching
9.Sorting & SearchingMandeep Singh
 
Algorithm By AMT.pptx
Algorithm By AMT.pptxAlgorithm By AMT.pptx
Algorithm By AMT.pptxAungMyintTun3
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingHub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingTiểu Hổ
 

Similar to Lecture 11.2 : sorting (20)

Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
 
Algorithms & Complexity Calculation
Algorithms & Complexity CalculationAlgorithms & Complexity Calculation
Algorithms & Complexity Calculation
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
shell and merge sort
shell and merge sortshell and merge sort
shell and merge sort
 
Lecture 2 data structures & algorithms - sorting techniques
Lecture 2  data structures & algorithms - sorting techniquesLecture 2  data structures & algorithms - sorting techniques
Lecture 2 data structures & algorithms - sorting techniques
 
Data Structure & Algorithms - Mathematical
Data Structure & Algorithms - MathematicalData Structure & Algorithms - Mathematical
Data Structure & Algorithms - Mathematical
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and Analysis
 
Lecture 4 asymptotic notations
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notations
 
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in Algoritm
 
Sorting
SortingSorting
Sorting
 
Lecture 3 insertion sort and complexity analysis
Lecture 3   insertion sort and complexity analysisLecture 3   insertion sort and complexity analysis
Lecture 3 insertion sort and complexity analysis
 
9.Sorting & Searching
9.Sorting & Searching9.Sorting & Searching
9.Sorting & Searching
 
Merge sort
Merge sortMerge sort
Merge sort
 
Algorithm By AMT.pptx
Algorithm By AMT.pptxAlgorithm By AMT.pptx
Algorithm By AMT.pptx
 
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & SearchingHub 102 - Lesson 5 - Algorithm: Sorting & Searching
Hub 102 - Lesson 5 - Algorithm: Sorting & Searching
 

More from Vivek Bhargav

Lecture 11.1 : heaps
Lecture 11.1 :  heapsLecture 11.1 :  heaps
Lecture 11.1 : heapsVivek Bhargav
 
Lecture 10 : trees - 2
Lecture 10 : trees - 2Lecture 10 : trees - 2
Lecture 10 : trees - 2Vivek Bhargav
 
Lecture 9: Binary tree basics
Lecture 9: Binary tree basicsLecture 9: Binary tree basics
Lecture 9: Binary tree basicsVivek Bhargav
 
Lecture 7 & 8: Stack & queue
Lecture 7 & 8: Stack  & queueLecture 7 & 8: Stack  & queue
Lecture 7 & 8: Stack & queueVivek Bhargav
 
Lecture 6: linked list
Lecture 6:  linked listLecture 6:  linked list
Lecture 6: linked listVivek Bhargav
 
Lecture 5: Asymptotic analysis of algorithms
Lecture 5: Asymptotic analysis of algorithmsLecture 5: Asymptotic analysis of algorithms
Lecture 5: Asymptotic analysis of algorithmsVivek Bhargav
 
Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: FunctionsVivek Bhargav
 
Lecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationLecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationVivek Bhargav
 
Lecture 2: arrays and pointers
Lecture 2: arrays and pointersLecture 2: arrays and pointers
Lecture 2: arrays and pointersVivek Bhargav
 
Lecture 1: basic syntax
Lecture 1: basic syntaxLecture 1: basic syntax
Lecture 1: basic syntaxVivek Bhargav
 

More from Vivek Bhargav (10)

Lecture 11.1 : heaps
Lecture 11.1 :  heapsLecture 11.1 :  heaps
Lecture 11.1 : heaps
 
Lecture 10 : trees - 2
Lecture 10 : trees - 2Lecture 10 : trees - 2
Lecture 10 : trees - 2
 
Lecture 9: Binary tree basics
Lecture 9: Binary tree basicsLecture 9: Binary tree basics
Lecture 9: Binary tree basics
 
Lecture 7 & 8: Stack & queue
Lecture 7 & 8: Stack  & queueLecture 7 & 8: Stack  & queue
Lecture 7 & 8: Stack & queue
 
Lecture 6: linked list
Lecture 6:  linked listLecture 6:  linked list
Lecture 6: linked list
 
Lecture 5: Asymptotic analysis of algorithms
Lecture 5: Asymptotic analysis of algorithmsLecture 5: Asymptotic analysis of algorithms
Lecture 5: Asymptotic analysis of algorithms
 
Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: Functions
 
Lecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationLecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory Allocation
 
Lecture 2: arrays and pointers
Lecture 2: arrays and pointersLecture 2: arrays and pointers
Lecture 2: arrays and pointers
 
Lecture 1: basic syntax
Lecture 1: basic syntaxLecture 1: basic syntax
Lecture 1: basic syntax
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 

Recently uploaded (20)

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 

Lecture 11.2 : sorting

  • 1. Placement Preparation Sorting and Heaps Varun Raj B.Tech, CSE
  • 2. Prerequisites • You must know array properly. • You must be familiar with pointers and writing basic loops • You must have some basic idea of time complexity
  • 3. Aim of Lecture ● Selection Sort/Bubble Sort ● Insertion Sort ● Merge Sort ● Heaps and Heapsort ● Quick Sort (If possible)
  • 4. Motivation Sorting is any process of arranging items according to value. In computer science, sorting is one of the most extensively researched subjects because of the need to speed up the operation on thousands or millions of records during a search operation
  • 5. The real reason. ● The real reason we are studying sorting is because be it any coding question in any interview the candidate is expected to know the basic of the sorting and sorting questions are the most expected questions to be asked
  • 6. Selection Sort The most intuitive sorting algorithm. Works by selecting the smallest element of the array and placing it at the head of the array. Then the process is repeated for the remainder of the array the next smallest element is selected and put into the next slot, and so on down the line
  • 7. Demo #1 Code of Selection Sort
  • 8. Exercise #1 ● Write a program that does selection sort on a set of integers ● Some pointers- ● You will need two loops ● You will need a variable that stores the current minimum and then you will have to swap it with the head.
  • 9. Analysing Complexity • In the 1st step the algorithm the for loop runs n-1 times. • In the second step the for loop runs n-2 times since the 1st element is set • Hence the time taken is n-1+n-2+n-3……..+1=n*(n-1)/2 That is O(n^2) • The thing to note is that the complexity is O(n^2) for best, average and worst case. • The space complexity is O(1) that is no extra space is used since the algorithm works only on the input array
  • 10. Bubble Sort The bubble sort works by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary. This process is repeated as many times as necessary, until the array is sorted
  • 11. Demo #2 Code For Bubble Sort
  • 12. Exercise #2 ● Write a program that does bubble sort on a set of integers ● Some pointers- ● You will need two loops • At the end of 1st step the maximum reaches the last position .At the end of second step the 2nd maximum reaches the 2nd last position
  • 13. Analysing Complexity for Bubble Sort • In the 1st step the algorithm the for loop runs n times. • In the second step the for loop runs n-1 times since the 1st element is set • Hence the time taken is n+n-1+n-2……..+1=n*(n+1)/2 That is O(n^2) • The thing to note is that the complexity is O(n^2) for best, average and worst case. • The space complexity is O(1) that is no extra space is used since the algorithm works only on the input array
  • 14. Some Improvements To Bubble Sort On Close Observation we observe that even in the best case Bubble Sort takes O(n^2) time this can be reduced to O(n) that is in a perfectly sorted array bubble sort will only take O(n) time to terminate(which is already sorted) The idea behind this is that at each outer loop iteration keep a counter so that if in it’s inner loop iteration no swapping was done this means that the array is already sorted and no further outer loop iterations need to be done and the array is sorted.So terminate the code
  • 15. Demo #3 ● This improves only the best case running time of bubble sort the worst case still remains O(n^2) ● The complexity is O(n^2) for average and worst case. ● For best case complexity is O(n) that is already sorted array
  • 16. Insertion Sort It inserts each element of the array into its proper position, leaving progressively larger stretches of the array sorted
  • 17. Demo Code for insertion sort
  • 18. Analysing Complexity for Insertion Sort • In the 1st step the algorithm the for loop runs 0 times. • In the second step the for loop runs 1 times (worst case) Hence the time taken is 1+2+3….n-1=n*(n-1)/2 That is O(n^2) (worst case) • The thing to note is that the complexity is O(n^2) for average and worst case. • The best case time complexity is O(n). • The space complexity is O(1) that is no extra space is used since the algorithm works only on the input array
  • 19. Merge Sort MergeSort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself recursively for the two halves and then merges the two sorted halves.
  • 20. Merge Sort-Intiution The main concept here is recursion The Merge Sort takes an array from 1 to n and calls itself on the array [1,n/2] and [n/2+1,n] recursively both these subparts are sorted so too sort two completely sorted list we only merge them
  • 21. Demo Code for merge sort Its little complicated so I would like you to practise properly Some common errors • Base case of recursion • Problems with merging especially when one half crosses the midpoint (Explained)
  • 22. Analysing Complexity for Merging Sort • There is some trick involved in finding the time complexity of Merge Sort . The time complexity is O(nlogn) Here log refers to base 2. • Proof- • T(n)=2*T(n/2) +cn where c is any constant • The solution to this equation is k*nlogn the proof follows from substitution and something you can look up online or I can do on the board. • The space complexity of this algorithm is O(n) since we are using an extra array
  • 23. Some remarks about Merge Sort • Merge Sort is the fastest algorithm you have seen till now.Its complexity is O(n*logn) and for large n it is faster than any quadratic algorithm for large input • Sometimes for small input merge sort may become slower than insertion sort due to constant factors.Hence for small input prefer insertion sort • The space complexity is O(n) that is an extra array is required this is the price we had to pay for a faster algorithm. • We will see now that Heaps offer us time complexity of O(nlogn) with no extra space required but it has a little sophisticated code.
  • 24. Some Concluding Remarks - ● We learnt 3 quadratic time sorting algorithms –Selection Sort, Insertion Sort, Bubble Sort ● We learnt to optimise bubble sort for best case ● The general advice is that whenever using a quadratic time algorithm use insertion sort. (The reason for this is given as an exercise at the last slide) ● Merge Sort trumps all the algorithm given large enough input, however for input as small as 10 insertion sort will be faster
  • 25. Extra Questions I am not going to discuss the answer to these questions in the class, however you could ask this question on facebook group or personally message me. These questions are for personal enhancement , maybe you could encounter this question in the placement interview/test maybe not • Insertion Sort-Prove that the time complexity of insertion sort is O(n+x) where x is the number of inversions in the input array.Here inversion refers to the pair (ai, aj) with i<j but ai >aj. • Merge Sort- The time complexity of Merge Sort is O(nlogn) .Prove that no sorting algorithm in the world that uses comparision sorting can be asymptotically faster than this