Consider the following Java code:
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.print("Sorted array: ");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Explain the purpose and functionality of the given selectionSort
method. Use the provided Java code and provide a step-by-step explanation of how the selectionSort
method works.
Create a markdown document with the question prompt and the answer.
The selectionSort
method is an implementation of the selection sort algorithm in Java. This algorithm divides the input array into two subarrays: a sorted subarray and an unsorted subarray. It repeatedly selects the minimum element from the unsorted subarray and swaps it with the first element of the unsorted subarray, effectively expanding the sorted subarray on each iteration.
Step-by-step explanation of the selectionSort
method:
selectionSort
method takes an integer array arr
as a parameter and sorts it in ascending order.n
with the length of arr
.i = 0
to n-1
. It represents the index of the current element being considered for placement in the sorted subarray.min_idx
is initialized with the value of i
. This variable stores the index of the minimum element found in the unsorted subarray.j = i+1
, iterates through the unsorted subarray to find the minimum element. It compares the element at index j
with the element at index min_idx
. If the element at j
is smaller, min_idx
is updated with the index j
.arr[min_idx]
.arr[min_idx]
is stored in a temporary variable temp
.arr[min_idx]
is replaced with the value at arr[i]
, effectively swapping the minimum element with the first element of the unsorted subarray.temp
is assigned to arr[i]
, placing the minimum element in the correct position in the sorted subarray.main
method, an example array [64, 25, 12, 22, 11]
is created.selectionSort
method is called with the example array as an argument to sort it in ascending order.Note: The selection sort algorithm has a time complexity of O(n^2) in worst and average cases.