Implement the selection sort algorithm to sort an array of integers in ascending order. Write a Java method named selectionSort
that takes an array of integers as input and returns the sorted array.
public static int[] selectionSort(int[] arr)
The input parameter arr
is an array of integers. The length of the array is n (1 ≤ n ≤ 1000) and the elements of the array are integers (-10^9 ≤ arr[i] ≤ 10^9).
The method should return the sorted array in ascending order.
Input:
arr = {64, 25, 12, 22, 11}
Output:
[11, 12, 22, 25, 64]
The selection sort algorithm works by repeatedly finding the minimum element from the unsorted part of the array and putting it at the beginning. In each iteration, the smallest element is selected from the unsorted portion and swapped with the element at the current position.
Here are the steps to perform selection sort on the given input array:
Hence, the output of the selectionSort
method when called with {64, 25, 12, 22, 11}
as input will be [11, 12, 22, 25, 64]
.
public static int[] selectionSort(int[] arr) {
// Traverse through all array elements
for (int i = 0; i < arr.length - 1; i++) {
// Assume the current element is the minimum
int minIndex = i;
// Find the minimum element in the unsorted part of the array
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the minimum element with the current element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
return arr;
}