1. Brute Force (Selection Sort)
Intuition
Selection sort scans the unsorted portion of the array to find the minimum value and places it at the beginning.
Algorithm
- Step 1: Iterate i from 0 to n - 1.
- Step 2: Find index minIdx of smallest element in nums[i...n-1].
- Step 3: Swap nums[i] with nums[minIdx].
Brute Force (Selection Sort) Trace
2 of 2 questions left todayPhase 1 — Setup: Algorithm initializes tracking variables and sets initial inspection pointers for Heap Sort
Phase 1 — Setup: Algorithm initializes tracking variables and sets initial inspection pointers for Heap Sort.
#include <iostream>#include <vector>#include <algorithm> class Solution {public: void selectionSort(std::vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n - 1; i++) { int minIdx = i; for (int j = i + 1; j < n; j++) { if (nums[j] < nums[minIdx]) { minIdx = j; } } std::swap(nums[i], nums[minIdx]); } }}; int main() { Solution sol; std::vector<int> nums = {4, 10, 3, 5, 1}; sol.selectionSort(nums); std::cout << "Selection Sorted: "; for (int x : nums) std::cout << x << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Selection Sort). - Space complexity:
O(1)— Space complexity for Brute Force (Selection Sort).
Why Brute Force Doesn't Scale:
Selection Sort O(N2) makes N2 comparisons. Heap Sort replaces linear minimum finding with logarithmic sift-down, reducing comparisons by orders of magnitude.
For N = 1,000,000: Selection sort requires ~1012 comparisons (~16 minutes); Heap Sort requires ~20,000,000 operations (~0.05 seconds).