lecture-5 (2)
lecture-5 (2)
Lecture No. 5
1
Selection Sort
• Big Idea
Orders a list of values by repeatedly putting the
smallest unplaced value into its final position.
Algorithm:
– Look through the list to find the smallest value.
– Swap it so that it is at index 0.
– Look through the list to find the second-
smallest value.
– Swap it so that it is at index 1.
...
– Repeat until all values are in their proper
places.
Selection Sort – Code Snippet
Pass1
19 12 30 14 18 Exchange
12 19 30 14 18 No Exchange
12 19 30 14 18 Exchange
12 19 14 30 18 Exchange
12 19 14 18 30 End of Pass1
Note: Largest element is at the end of the list
Trace of Bubble Sort Algorithm
Pass 2
12 19 14 18 30 No Exchange
12 19 14 18 30 Exchange
12 14 19 18 30
Exchange
12 14 18 19 30
No Exchange
12 14 18 19 30
End of Pass2
Note:
• 2nd Largest element is in its correct position
• Bubble Sort will terminate after two more passes
Trace of Bubble Sort Algorithm
Observe:
• Bubble Sort will continue with passes till termination
though list may be sorted after an intermediate Pass.
• Like in above example, list is sorted after 2nd Pass but
Bubble Sort will terminate only after 4 Passes
Bubble Sort – Pseudo Code
Pseudo Code
begin
for i = 1 to n−1
for j = 1 to n−i
if (a[j]> a[j+ 1]) then
Swap (a[j],a[j+ 1])
end
• Invariant?
Bubble Sort - Analysis
Analysis:
• Irrespective of the nature of input, the number of passes to
be made is n−1
• The number of comparisons during ith pass is n−i.
The total number of comparisons is =
(n−1) + (n−2) +...+ 2 + 1 = n(n-1)/2 = O(n2)
Bubble Sort - Analysis
Analysis (Notes)
• Analysis does not depend on particular instance
• Therefore Best Case = Worst case = O(n2)
• Number of swap operations
Best Case – O(1)
Worst Case - O(n2)
Exercise: Identify the instances of best case and worst case
• Bubble sort is an in-place algorithm.
It performs all computation in the original array
and no other array is used.
Hence, the space complexity is O(1).
Bubble Sort - Variation
• As observed in the example the list is sorted well
before (n-1) passes.
• Question
How to take advantage of this?
• Observe
If no exchanges are made in a pass then the list is
sorted.
• Exercise
Design an algorithm that incorporates the above
idea & find the number of comparisons it makes.
Sorting - Summary
Summary – Time Complexity
Best Case Worst Case
Insertion Sort O(n) O(n2)
Selection Sort O(n2) O(n2)
Bubble Sort O(n2) O(n2)
Average Case
Given a sequence what is the Expected Number
of inversions?
Let
Average Case
Therefore, by linearity of expectation
And
So