Question:
Implement the selection sort algorithm in Java to sort an array of integers in ascending order. Write a method selectionSort
that takes an integer array named arr
as a parameter and returns the sorted array.
Your implementation must perform the following steps:
public class SelectionSort {
public static int[] selectionSort(int[] arr) {
// Your implementation here
}
public static void main(String[] args) {
int[] arr = {5, 3, 2, 4, 1};
int[] sortedArr = selectionSort(arr);
// Print the sorted array
for (int i = 0; i < sortedArr.length; i++) {
System.out.print(sortedArr[i] + " ");
}
}
}
Explanation:
To implement the selection sort algorithm, follow these steps:
Declare a variable n
and assign the length of the input array arr
to it. This represents the number of elements in the array.
Iterate over the array from index 0 to n-1
. Let the current index be i
. This index represents the start of the unsorted part of the array.
Declare a variable minIndex
and assign i
to it. This will store the index of the minimum element found in the unsorted part of the array.
Iterate over the array from i+1
to n-1
. Let the current index be j
. This index represents the rest of the unsorted part of the array.
Inside the inner loop, check if the element at index j
is less than the element at index minIndex
. If so, update minIndex
to j
.
After the inner loop ends, swap the element at index i
with the element at index minIndex
using a temporary variable.
Repeat steps 3-6 until the outer loop ends, i.e., when i = n-1
.
Finally, return the sorted array arr
.
The time complexity of the selection sort algorithm is O(n^2), where n is the number of elements in the array. The space complexity is O(1), as it only requires a few variables for comparisons and swapping.
Answer (Java):
public static int[] 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;
}
return arr;
}
public static void main(String[] args) {
int[] arr = {5, 3, 2, 4, 1};
int[] sortedArr = selectionSort(arr);
// Print the sorted array
for (int i = 0; i < sortedArr.length; i++) {
System.out.print(sortedArr[i] + " ");
}
}
The output of the above code will be: 1 2 3 4 5
.