Professional Documents
Culture Documents
Department of M.Tech Computer Science & Engineering: Fundamentals of Algorithm Analysis
Department of M.Tech Computer Science & Engineering: Fundamentals of Algorithm Analysis
www.skcet.ac.in
BRUTE FORCE
04/07/2023 2
CONT…
04/07/2023 3
CONT…
04/07/2023 4
CONT…
04/07/2023 5
CONT…
04/07/2023 6
EXAMPLES
• Sequential search
• String matching algorithm
• Travelling sales man problem
• Knapsack problem
04/07/2023 7
EXAMPLE
04/07/2023 8
…..
…..
04/07/2023 9
TYPES OF ALGORITHMS
• Sorting Algorithms
• Search Algorithms
• Compression Algorithms
04/07/2023 10
04/07/2023 11
PSUEDO CODE
• Graph
• Dynamic Programming
• Sorting
• Searching
• Strings
• Math
• Computational Geometry
• Optimization
• Miscellaneous.
04/07/2023 13
SELECTION SORT
04/07/2023 14
CONT..
04/07/2023 15
CONT..
04/07/2023 16
CONT..
min ← I
for j ← i + 1 to n − 1 do
if A[j ] < A[min]
min ← j
swap A[i] and A[min]
04/07/2023 17
CONT…
04/07/2023 18
CONT..
04/07/2023 19
04/07/2023 Dr.D.Mansoor Hussain, AP/CSE 20
PROPERTIES
• Not stable
• O(1) extra space
• Θ(n2) comparisons
• Θ(n) swaps
• Not adaptive
04/07/2023 21
KEY
04/07/2023 22
CONT..
04/07/2023 23
CONT..
04/07/2023 24
CONT..
04/07/2023 26
ALGORITHM
for i = 1:n,
k=i
for j = i+1:n,
if a[j] < a[k], k = j
→ invariant: a[k] smallest of a[i..n]
swap a[i,k]
→ invariant: a[1..i] in final position
end
04/07/2023 27
04/07/2023 28
64 25 12 22 11
0 1 2 3 4
64 25 12 22 11
0 0 1 2 3
11 25 12 22 64
0 1 0 1 2
11 12 25 22 64
0 1 2 0 1
11 12 22 25 64
0 1 2 3 0
11 12 22 25 64
0 1 2 3 4
11 12 22 25 64
04/07/2023 29
How Selection Sort Works?
• 20,12,10,15,2
04/07/2023 30
04/07/2023 31
04/07/2023 32
First Iteration
04/07/2023 33
Second Iteration
04/07/2023 34
Third Iteration
04/07/2023 35
Fourth Iteration
04/07/2023 36
Assume that the array A=[7,5,4,2] needs
to be sorted in ascending order
• At ith iteration, elements from position 0 to i-1
will be sorted.
04/07/2023 37
arr[] = 64 25 12 22 11
arr[] = 64 25 12 22 11 // Find the minimum element in
arr[0...4] and place it at beginning
11 12 22 25 64
04/07/2023 Dr.D.Mansoor Hussain, AP/CSE 38
Time Complexity
04/07/2023 40
Number of comparisons: (n - 1)+(n - 2)+(n - 3)+….+1
= n(n - 1) / 2 nearly equals to n2.
Complexity = O(n2)
04/07/2023 41
Also, we can analyze the complexity by simply
observing the number of loops.
There are 2 loops so the complexity is n*n = n2.
•Worst Case Complexity: O(n2)
If we want to sort in ascending order and the array
is in descending order then, the worst case occurs.
Space Complexity:
• Space complexity is O(1) because an extra
variable temp is used.
04/07/2023 43
Selection Sort Applications
The selection sort is used when: