Answer:
Following method can be used for sorting an array with selection sort.
public class SelectionSortExample {
public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8};
       selectionSort(arr);
       }
// Bubble Sort method
public static void selectionSort(int[] arr) {
int n = arr.length;
boolean swapped;
// Outer loop for all passes
for (int i = 0; i < n-1; i++) {
swapped = false;
// Inner loop for comparisons in each pass
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
swapped = true;
}
}
// If no swaps were done in this pass, the array is already sorted
if (!swapped) break;
}
}
}
}
Explanation:
We initialize an integer array arr and pass it to the selectionSort() method for sorting. Inside the selectionSort() method, we define an integer variable n to store the length of the array.
We use the following outer loop to iterate through each element of the array:
for (int i = 0; i < n-1; i++) {
Within this loop, we add a nested loop to compare the current element with the rest of the array:
for (int j = i + 1; j < n; j++) {
Before entering the inner loop, we initialize a boolean variable swapped = false; to track if any swapping occurs.
Inside the nested loop, we compare the current ith element with the jth element. If the ith element is greater than the jth element, we swap them to ensure smaller elements come first. The swapping is performed as follows:
if (arr[i] > arr[j]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
swapped = true;
}
If no swapping occurs during an iteration of the inner loop (swapped == false), we break out of the loop early to optimize performance.