📅 Date: Jan 19, 2026
🔥 Topic: Comparison & STL Sort()
⚔️ The Battle of Basic Sorts
I've learned three algorithms. All of them are O(n²), but they behave differently.
| Algo | Best Use Case |
|---|---|
| Bubble | Only for learning logic. Too many swaps. |
| Selection | Good when memory writes are expensive (fewer swaps). |
| Insertion | Best if data is nearly sorted or very small. |
🚀 The Pro Way: std::sort()
In competitive programming, we don't write Bubble Sort. We use C++'s built-in sort function which uses a hybrid algorithm (IntroSort) and runs in O(n log n). Much faster!
#include <iostream>
#include <algorithm> // Required header
#include <vector>
using namespace std;
int main() {
vector<int> v = {4, 2, 5, 1, 3};
// The Magic Line
sort(v.begin(), v.end());
for(int x : v) cout << x << " ";
return 0;
}
💠Thoughts
Knowing how Bubble/Insertion sort works helps build logic, but knowing std::sort() helps clear online assessments. Next up: Strings or Pointers?
No comments:
Post a Comment