Algo Lec 3
Algo Lec 3
Complexity Analysis:
What is Sorting?
Sorting is the process of arranging
elements in a specific order (ascending
or descending).
o Example: Sorting numbers ([3, 1,
4, 5, 2] → [1, 2, 3, 4, 5])
o Sorting strings (["Banana",
"Apple", "Cherry"] → ["Apple",
"Banana", "Cherry"])
Why Sorting is Important?
Sorting is crucial for:
o Efficient Searching: Faster
searching algorithms (e.g., binary
search).
o Data presentation: Better for
reporting, financial data, etc.
o Data Storage and Processing:
Sorting is used in databases,
Design and Analysis of Algorithms 2
Insertion Sort:
Example Walkthrough (Step-by-Step)
Using the array [5, 2, 9, 1, 5, 6]:
1. Start with the second element
(2): Compare with 5. Shift 5 to the
right and place 2 at the start.
Array after pass 1: [2, 5, 9, 1, 5, 6]
2. Move to the third element (9): No
change, as 9 is greater than 5.
2 2
Design and Analysis of Algorithms 3
3 3
Design and Analysis of Algorithms 4
Pseudocode
InsertionSort(array, n):
FOR i = 1 TO n - 1:
key = array[i]
4 4
Design and Analysis of Algorithms 5
j=i-1
WHILE j >= 0 AND array[j] > key:
array[j + 1] = array[j] // Shift
larger element to the right
j=j-1
ENDWHILE
array[j + 1] = key // Insert key
in its correct position
ENDFOR
5 5
Design and Analysis of Algorithms 6
6 6
Design and Analysis of Algorithms 7
Complexity Analysis
Case Explanation Complexity
Array is already
Best sorted. Inner loop
O(n)
Case runs only once for
each element.
Array is sorted in
Worst reverse. Inner loop
O(n²)
Case runs i times for each
iteration.
Elements are in
random order. On
Average
average, half of the O(n²)
Case
sorted portion is
checked.
7 7
Design and Analysis of Algorithms 8
8 8
Design and Analysis of Algorithms 9
9 9
Design and Analysis of Algorithms 10
Time Complexity:
o For n elements, the number of
comparisons = n-1.
o Total operations = O(n).
Worst Case Analysis
The worst case occurs when the array
is sorted in reverse order.
Key Observations:
For every element, all previous
o
Real-World Applications of
Complexities
1.Best Case (O(n)):
o Useful for nearly sorted datasets.
10 10
Design and Analysis of Algorithms 11
11 11
Design and Analysis of Algorithms 12
3. Loops
Variable Cost Factors:
1. Operations dependent on input
size, e.g.:
1. Comparisons (array[j] > key).
2. Shifts (array[j + 1] = array[j]).
12 12