1. Selection Sort (Brute Force)
Intuition
For each index i from 0 to n-1: find the index minIdx of the minimum element in nums[i..n-1]. Swap nums[i] with nums[minIdx]. Takes O(n2) time.
When to apply: Use for pedagogical baseline of in-place comparison sorts.
Selection Sort Trace
2 of 2 questions left todayArray: [5, 2, 3, 1]
Array: [5, 2, 3, 1]. i = 0. Find minimum in nums[0..3].
public class Main { public static class Solution { public int[] sortArray(int[] nums) { int n = nums.length; 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; } int temp = nums[i]; nums[i] = nums[minIdx]; nums[minIdx] = temp; } return nums; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {5, 2, 3, 1}; System.out.println("Sorted Array: " + java.util.Arrays.toString(sol.sortArray(nums))); }}Time & Space Complexity
- Time complexity:
O(n^2)— n*(n-1)/2 comparisons in the worst case. - Space complexity:
O(1)— O(1) auxiliary variables.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.