Algorithm-Lecture4 - Sorting-1
Algorithm-Lecture4 - Sorting-1
Lecture- 4
Algorithms Classification &
Sorting-I
No. of Steps Upper bound n large
Algorithm 1 g(n) = 3n
f(n) = 2n+3
O(n)
Algorithm 2 f(n) = 4n+8 g(n) =5n
O(n3)
O(log n)
2
“Asymptotic Analysis”
Calculating Running Determine O-notation
Time f(n) (upper bounds)
f(n) a polynomial .. f(n) =Z 3n2 + 4n
• Use the pseudo code
• Ignore constants Special case:
• Consider Coding If is f(n) a polynomial of degree d,
implementation then f(n) is O(nd)
• By Function
• By Implementation
• By Design Paradigm
Classification of Algorithms
Selection Algorithms
Arithmetic Algorithms
Text Algorithms
Classification by implementation
Recursive or iterative
Deterministic or non-deterministic
Logical or procedural
Serial or parallel
Using graphs
Heuristic
Bubble Sort
Selection Sort
Insertion
Sort Heap
Sort Quick
Sort Merge
Sort
Radix Sort
Bucket Sort
In-Place vs Not-In-Place algorithm
In-place : In In-Place algorithm, no additional data structure
or array is required for sorting.
Bubble Sort
Selection Sort
Insertion
Sort Heap
Sort Quick
Sort
Element Uniqueness
Given a set of n items, are they all unique or are there any
duplicates? Sort them and do a linear scan to check adjacent
pairs
Applications of Sorting
Mode
Text Functions
Pseudocode:
for i = 1:n
k = i
for j = i+1:n
if a[j] < a[k], k = j
swap a[i,k]
end
Selection Sort Analysis
77 42 35 12 101 5
"Bubbling Up" the Largest Element
Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise
comparisons and swapping
1 2 3 4 5 6
42
77 ap4277 35 12 101
Sw
5
"Bubbling Up" the Largest
Element
Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise
comparisons and swapping
1 2 3 4 5 6
77 35 ap 35
42 77 12 101 5
Sw
"Bubbling Up" the Largest
Element
Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise
comparisons and swapping
1 2 3 4 5 6
7712 ap 12
42 35 77 101 5
Sw
"Bubbling Up" the Largest
Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise
comparisons and swapping
1 2 3 4 5 6
42 35 12 77 101 5
No need to swap
"Bubbling Up" the Largest
Element
• Traverse a collection of elements
– Move from the front to the end
– “Bubble” the largest value to the end using pair-wise
comparisons and swapping
1 2 3 4 5 6
42 35 12 77 5 ap 101
5
101 Sw
"Bubbling Up" the Largest Element
1 2 3 4 5 6
42 35 12 77 5 101
1 2 3 4 5 6
42 35 12 77 5 101
1 2 3 4 5 6
42 35 12 77 5 101
1 2 3 4 5 6
35 12 42 5 77 101
1 2 3 4 5 6
N-1
12 35 5 42 77 101
1 2 3 4 5 6
12 5 35 42 77 101
1 2 3 4 5 6
5 12 35 42 77 101
Bubble Sort Pseudo Code
for i = 1 to n do
for j = n to i+1 do
If A[A] < A[j-1] then
Exchange A[j] ↔
A[j-1]