To find the minimum number of swaps required to make an array sorted, you can use the concept of selection sort. Here’s an example implementation in Java:
public class MinimumSwaps {
public static int findMinSwaps(int[] arr) {
int swaps = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
// Find the index of the minimum element in the unsorted portion of the array
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the minimum element with the current element if necessary
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
swaps++;
}
}
return swaps;
}
public static void main(String[] args) {
int[] arr = {4, 2, 1, 5, 3};
int minSwaps = findMinSwaps(arr);
System.out.println("Minimum swaps required: " + minSwaps);
}
}
In this example, the findMinSwaps
method takes an array as input and returns the minimum number of swaps required to sort the array. It uses the selection sort algorithm to find the minimum element in each iteration and swaps it with the current element if necessary. The main
method demonstrates the usage of the findMinSwaps
method with a sample array.
In the example, the array {4, 2, 1, 5, 3}
is given as input. The minimum number of swaps required to sort this array is 3. The output of the program would be:
Minimum swaps required: 3
This indicates that by performing 3 swaps, the array can be sorted in ascending order.