Selection Sort in Java: Program and Logic
Sort an integer array in ascending order using selection sort.
- Time
O(n^2) in every case - Space
O(1) - Hints3
- Read3 min
Selection sort in Java finds the smallest value in the unsorted part and swaps it into the first unsorted place. Repeat for each place until one element is left. It always makes n(n - 1) / 2 comparisons, so the time is O(n^2), but it needs at most n - 1 swaps and O(1) extra space.
Problem statement
Write a program for selection sort in Java. Given an int array, sort it in
ascending order in place, without Arrays.sort.
The array is split into two parts: sorted on the left, unsorted on the right. Each step selects the smallest unsorted value and adds it to the sorted part.
An integer array arr of length n.
The same array in ascending order.
Examples
[29, 10, 14, 37, 13][10, 13, 14, 29, 37]10 is selected first, then 13, 14 and 29.
[4, 4, -1][-1, 4, 4]-1 moves to the front. The equal values need no more work.
Constraints
- 0 <= n <= 5000, as the time is quadratic
- Duplicates and negative numbers are allowed
Think before you code
Reveal the questions to ask yourself first
- Which value belongs at index 0?
- Should you store the smallest value, or its index?
- How many swaps does one pass need?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- For each index
ifrom 0 ton - 2, setmin = i. - Scan
jfromi + 1to the end. Ifarr[j] < arr[min], setmin = j. - After the scan, swap
arr[i]andarr[min]if they are different positions.
The scan is the same idea as find the smallest element, run again on a smaller part each time.
Dry run
Walk through the example step by step
[29, 10, 14, 37, 13]:
i | smallest from i | swap | array after
--+-----------------+----------+---------------------
0 | 10 at index 1 | 29, 10 | [10, 29, 14, 37, 13]
1 | 13 at index 4 | 29, 13 | [10, 13, 14, 37, 29]
2 | 14 at index 2 | none | [10, 13, 14, 37, 29]
3 | 29 at index 4 | 37, 29 | [10, 13, 14, 29, 37]
Solution
Reveal the full Java solution
import java.util.Arrays;
public class SelectionSort {
static void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
public static void main(String[] args) {
int[] a = {29, 10, 14, 37, 13};
sort(a);
System.out.println(Arrays.toString(a));
int[] b = {4, 4, -1};
sort(b);
System.out.println(Arrays.toString(b));
}
}Output of this selection sort in Java code:
[10, 13, 14, 29, 37]
[-1, 4, 4]
Selection sort in Java for Class 10
School questions may ask you to take input with Scanner and write everything in main.
This selection sort in Java simple program does that. The input is the size and then
the numbers.
import java.util.Scanner;
public class SelectionSortInput {
// Sample input: 5 64 25 12 22 11
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[min]) {
min = j;
}
}
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
Output for the sample input:
11 12 22 25 64
In a written answer, describe the variables: n is the size, min is the index of the
smallest value, temp helps the swap. Also check your own board's syllabus and format.
Selection sort in Java: descending order
Select the largest value each time.
import java.util.Arrays;
public class SelectionDescending {
public static void main(String[] args) {
int[] a = {29, 10, 14, 37, 13};
for (int i = 0; i < a.length - 1; i++) {
int max = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] > a[max]) {
max = j;
}
}
int temp = a[i];
a[i] = a[max];
a[max] = temp;
}
System.out.println(Arrays.toString(a));
}
}
[37, 29, 14, 13, 10]
Complexity and comparison
| Point | Selection | Bubble (with flag) | Insertion |
|---|---|---|---|
| Best time | O(n²) | O(n) | O(n) |
| Worst time | O(n²) | O(n²) | O(n²) |
| Most swaps or shifts | n - 1 swaps | n(n - 1) / 2 swaps | n(n - 1) / 2 shifts |
| Stable | No | Yes | Yes |
Why is it not stable? Take [4a, 4b, 1]. The first swap exchanges 4a and 1, which
gives [1, 4b, 4a]. The two 4s have changed their order.
Choose this selection sort in Java program when writing to memory costs a lot, since it swaps so little. See bubble sort, insertion sort, and the Java coding questions. The Java full stack course covers Java from the start.
O(n^2) in every caseO(1)Review before the interview
Common mistakes
- Swapping inside the inner loop. It can still sort, but it makes many extra swaps.
- Comparing with arr[i] instead of arr[min], which loses the smallest index.
- Starting j at 0, which breaks the sorted part.
- Saying the best case is O(n). Selection sort always scans the whole unsorted part.
Edge cases to test
- Empty array or one element: the outer loop does not run.
- Already sorted: all comparisons still happen, but there are no swaps.
- All values equal: no swaps with the min != i check.
- Negative values and duplicates.
Interview follow-ups
- Can you make selection sort stable?
- Can you pick both the smallest and the largest in one pass?
- How many comparisons are made for n = 10?
Keep practising
Bubble Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemInsertion Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemFind the Smallest Element in an Array
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
