Implementation of the Selection Sort algorithm in Java
This is a simple and basic implementation of selection sort, which is primarily used for educational purposes due to its inefficiency for large datasets.
This is a simple and basic implementation of selection sort, which is primarily used for educational purposes due to its inefficiency for large datasets.
Original array: 64 25 12 22 11
Sorted array: 11 12 22 25 64
public class SelectionSort {
// Function to perform selection sort
public static void selectionSort(int[] array) {
int n = array.length;
// One by one, move the boundary of the unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted array
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
// Function to print the array
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(array);
// Perform selection sort
selectionSort(array);
System.out.println("Sorted array:");
printArray(array);
}
}
Original array:
64 25 12 22 11
Sorted array:
11 12 22 25 64
n is the number of elements in the array.First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.