Question:
Explain the selection sort algorithm and its implementation in Java. Provide a step-by-step explanation of how the selection sort algorithm works, and demonstrate its implementation through a Java code snippet.
Answer:
The selection sort algorithm is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and swapping it with the first unsorted element. This process continues until the entire array is sorted.
Here's the step-by-step explanation of the selection sort algorithm:
Now, let's demonstrate the implementation of the selection sort algorithm in Java:
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
In this Java implementation, we have a selectionSort
method that implements the selection sort algorithm. We loop through the array to find the minimum element in the unsorted portion and perform swaps as required. The main
method demonstrates the usage of the selectionSort
method on an array and prints the sorted array.
This code snippet illustrates the selection sort algorithm and its implementation in Java.