Selection Sort
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ arr.length ≤ 200 - ◆
-1000 ≤ arr[i] ≤ 1000 - ◆
Sort in non-decreasing order
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Collect Minimums into a New Array
GoodFor each output position, scan every value that hasn't been used yet, find the smallest one, and record it. Repeat until every value has been placed. This never touches the original array — it builds the sorted result in a brand-new array (with an auxiliary "used" marker per element), which costs O(n) extra memory that the in-place version doesn't need.
O(n²)O(n)1class Solution {
2 public int[] selectionSort(int[] arr) {
3 int n = arr.length;
4 boolean[] used = new boolean[n];
5 int[] result = new int[n];
6 for (int i = 0; i < n; i++) {
7 int minIdx = -1;
8 for (int j = 0; j < n; j++) {
9 if (!used[j] && (minIdx == -1 || arr[j] < arr[minIdx])) {
10 minIdx = j;
11 }
12 }
13 result[i] = arr[minIdx];
14 used[minIdx] = true;
15 }
16 return result;
17 }
18}Optimal — In-Place, Swap Into Position
OptimalGrow a sorted prefix from the left. For each position i, scan the rest of the array to find the index of the smallest remaining value, then swap it directly into position i. No second array is ever allocated — every value stays inside the original array the whole time, just getting swapped into its final resting spot one position at a time.
O(n²)O(1)1class Solution {
2 public int[] selectionSort(int[] arr) {
3 int n = arr.length;
4 for (int i = 0; i < n - 1; i++) {
5 int minIdx = i;
6 for (int j = i + 1; j < n; j++) {
7 if (arr[j] < arr[minIdx]) {
8 minIdx = j;
9 }
10 }
11 int temp = arr[i];
12 arr[i] = arr[minIdx];
13 arr[minIdx] = temp;
14 }
15 return arr;
16 }
17}