Quick Sort and Its Worst-Case Analysis
Quick Sort and Its Worst-Case Analysis
1. Choose a Pivot: Select an element from the array (e.g., first, last, random, or median).
2. Partitioning: Rearrange elements so that:
o Elements smaller than the pivot go to the left.
o Elements greater than the pivot go to the right.
3. Recursion: Recursively apply the above steps to the left and right subarrays until the
base case is reached (single-element subarrays).
Worst-Case Analysis:
The worst case occurs when the pivot selection leads to the most unbalanced partitions. This
happens in two common cases:
In the worst case, the recursive calls resemble a degenerate linked list structure, leading to
T(n) = T(n-1) + O(n).
T(n)=T(n−1)+O(n)
T(n) = T(n-2) + O(n-1) + O(n)
T(n)=O(1)+O(2)+⋯+O(n)
T(n) = O(n^2)
Quick Sort is often preferred for practical sorting due to its low constant factors and
efficient in-place sorting behavior, despite its worst-case potential.
Huffman Encoding
Huffman Encoding is a lossless data compression algorithm that assigns variable-length binary codes
to characters based on their frequencies. It ensures that more frequent characters get shorter codes,
while less frequent characters get longer codes.
2. Build a Min-Heap: Create a priority queue (min-heap) where each node represents a
character and its frequency.
o Remove the two nodes with the smallest frequency from the heap.
o Assign '0' to the left and '1' to the right at each level.
o To decode, follow the binary sequence from the root of the Huffman tree.
Example
Given String:
BCAADDDCCACACAC
Character Frequency
A 5
B 1
C 6
D 3
Step 2: Building the Huffman Tree
3. Combine C (6) and ABD (9) → Root node (CABD) with frequency 15.
(Root)
/ \
C ABD
0 / \
A BD
10 / \
B(110) D(111)
Huffman Codes:
• A → 10
• B → 110
• C→0
• D → 111
Step 4: Encoding
Complexity Analysis
• Encoding/Decoding: O(n)
Limitations
Requires prior frequency analysis, which may not be efficient for streaming data.
Not ideal for small text files where overhead can be significant.
Huffman Encoding is an essential technique for efficient data compression and is widely used in real-
world applications like file compression and data transmission.
Example
Given Matrices
A1(10×20)A_1 (10 \times 20)A1(10×20), A2(20×30)A_2 (20 \times 30)A2(20×30), A3(30×40)A_3 (30
\times 40)A3(30×40), A4(40×30)A_4 (40 \times 30)A4(40×30)
Possible Parenthesization
Complexity Analysis
• Subproblems: O(n^2)
• Transitions: O(n)
Advantages of MCM
Limitations
Both BFS and DFS are fundamental graph traversal algorithms used in various applications like
pathfinding, web crawling, network analysis, and AI search problems.
Concept
• Explores all neighbors at the current level before moving to the next level.
Algorithm Steps
o Dequeue a node.
Concept
Algorithm Steps
Use Cases
✔ Pathfinding in mazes/games.
✔ Cycle detection in graphs.
✔ Topological Sorting in DAGs (Dependency Resolution).
✔ Backtracking algorithms (e.g., Sudoku Solver, N-Queens).