🚀 Day 5: Merge Sort & Quick Sort in Java 🎯 Goals for Today
-
Understand the Divide and Conquer strategy
-
Learn and implement:
-
Merge Sort
-
Quick Sort
-
-
Analyze Time & Space Complexities
-
Solve intermediate-level sorting problems
📘 1. Merge Sort
A stable, divide-and-conquer sorting algorithm.
Time Complexity: O(n log n)
in all cases
Space Complexity: O(n)
(extra array)
✅ Logic:
-
Divide the array into two halves
-
Sort each half recursively
-
Merge the two sorted halves
🔹 Java Implementation
⚡ 2. Quick Sort
Quick and efficient, especially on average cases.
Time Complexity:
-
Best/Average:
O(n log n)
-
Worst:
O(n²)
(when pivot is worst chosen)
Space:O(log n)
(due to recursive calls)
✅ Logic:
-
Choose a pivot
-
Partition the array: elements < pivot go left, > pivot go right
-
Recursively sort left and right
🔹 Java Implementation
📊 3. Merge Sort vs Quick Sort
Feature | Merge Sort | Quick Sort |
---|---|---|
Time (Best) | O(n log n) | O(n log n) |
Time (Worst) | O(n log n) | O(n²) |
Space | O(n) | O(log n) |
Stable | ✅ Yes | ❌ No |
In-place | ❌ No | ✅ Yes |
Use Case | Linked lists | Arrays |
🧠 4. Practice Problems
Try these problems:
-
🔁 Kth Largest Element in Array – Use Quick Select
-
🧠 Count Inversions in Array – Use Merge Sort logic
📚 Homework for Day 5
-
Implement Merge Sort and Quick Sort
-
Solve 2 LeetCode problems involving sorting or partitioning
-
Try to write non-recursive quick sort (advanced)
-
Visualize Merge vs Quick: Try https://visualgo.net/en/sorting
🔜 Coming Up on Day 6:
-
Recursion Mastery
-
Backtracking intro (Subset, Permutations)
-
Understanding call stack and dry runs
Comments
Post a Comment