Selection Sort Example in Java
On this page (9sections)
Introduction
Selection Sort is a classic Java console program that demonstrates the concept with complete source code and sample output. Sorting algorithms arrange data in order — bubble, selection, merge, quick and heap sort.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.
Selection Sort Example Program
public class SelectionSort {
public static int[] method1(int[] arry){
for (int i = 0; i < arry.length - 1; i++){
int count = i;
for (int j = i + 1; j < arry.length; j++)
if (arry[j] < arry[count])
count = j;
int smallerNumber = arry[count];
arry[count] = arry[i];
arry[i] = smallerNumber;
}
return arry;
}
public static void main(String a[]){
int[] arry1 = {44,78,56,34,22,99,111,5};
System.out.println("array before sorting is ");
for(int i=0;i < arry1.length;i++){
System.out.println(arry1[i]);
}
int[] arry2 = method1(arry1);
System.out.println("Array after sorting is");
for(int i:arry2){
System.out.print(i);
System.out.println("");
}
}
}
Sample Output
Array before sorting is
44
78
56
34
22
99
111
5
Array after sorting is
5
22
34
44
56
78
99
111
When to use
Use this selection sort example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
for (int i = 0; i < arry.length - 1; i++){updates a variable used in the calculation or output. -
int count = i;updates a variable used in the calculation or output. -
for (int j = i + 1; j < arry.length; j++)updates a variable used in the calculation or output. -
The
ifstatement runs the nested code only when the condition is true. -
count = j;updates a variable used in the calculation or output. -
int smallerNumber = arry[count];updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.