1. Brute Force — Full Comparison Sort
Intuition
Call standard library sort on the array in O(N log N) time.
When to apply: When simplicity is preferred and k is close to N.
Algorithm
- Step 1: Sort arr ascending using standard library sort.
- Step 2: Return arr.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: void nearlySorted(vector<int>& arr, int k) { sort(arr.begin(), arr.end()); }}; int main() { Solution sol; vector<int> arr = {6, 5, 3, 2, 8, 10, 9}; sol.nearlySorted(arr, 3); cout << "Sorted (Brute Force): "; for (int x : arr) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— O(N log N) full sorting. - Space complexity:
O(1) auxiliary— O(1) auxiliary space.
Why Brute Force Doesn't Scale:
When k = 10 and N = 106, O(N log N) takes ~2 * 107 comparisons. O(N log k) takes ~3.3 * 106 comparisons (6x faster).
Min-Heap sorts 1,000,000 items with k = 10 in ~25ms.