✅ Day 4: Sorting Algorithms (Basic to Intermediate)
🎯 Goals for Today
-
Understand how sorting works and why it’s needed
-
Learn and implement:
-
Bubble Sort
-
Selection Sort
-
Insertion Sort
-
-
Analyze time & space complexities
-
Practice beginner sorting problems
📘 1. Why Sorting Matters
Sorting helps:
-
Optimize searching (e.g., binary search)
-
Solve problems like duplicates, frequency, etc.
-
Prepare data for algorithms like two pointers, greedy, divide & conquer, etc.
🔁 2. Sorting Algorithms
🔹 Bubble Sort
Repeatedly swap adjacent elements if they are in the wrong order.
-
Time Complexity: Worst →
O(n²)
, Best →O(n)
(already sorted) -
Space:
O(1)
🔹 Selection Sort
Find the minimum element and put it at the beginning.
-
Time Complexity: Always
O(n²)
-
Space:
O(1)
🔹 Insertion Sort
Build the sorted array one element at a time by inserting elements at the correct position.
-
Time Complexity: Best →
O(n)
, Worst →O(n²)
-
Space:
O(1)
🧠 3. Sorting Algorithm Comparison Table
Algorithm | Time Complexity (Best / Avg / Worst) | Space | Stable? |
---|---|---|---|
Bubble Sort | O(n) / O(n²) / O(n²) | O(1) | ✅ |
Selection Sort | O(n²) / O(n²) / O(n²) | O(1) | ❌ |
Insertion Sort | O(n) / O(n²) / O(n²) | O(1) | ✅ |
Try these:
-
Sort an array of 0s, 1s, and 2s (Dutch National Flag)
-
Check if an array is sorted and rotated
-
Count the number of swaps required to sort the array
-
Sort a nearly sorted (k-sorted) array
You can also implement a custom comparator or reverse order sort (forward-thinking Java practice).
📚 Homework for Day 4
✅ Implement all three sorting algorithms
✅ Solve 2 sorting-based problems from LeetCode:
Would you like solutions for these 2 LeetCode problems?
⏭️ What’s Coming on Day 5:
-
Advanced Sorting: Merge Sort, Quick Sort
-
Time Complexity Analysis
-
Recursion involved in sorting
Comments
Post a Comment